Python os.close()方法

Python的os.close()方法关闭文件描述符fd的关联。

语法

以下是close()方法的语法 -

os.close(fd)

参数

  • fd − 这是文件的文件描述符。

返回值

  • 此方法不返回任何值。

注意 - 此功能适用于低级I/O,并且必须应用于os.open()pipe()返回的文件描述符。

示例

以下示例显示了close()方法的用法。

#!/usr/bin/python3
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string
line = "this is test" 

# string needs to be converted byte object
b = str.encode(line)
os.write(fd, b)

# Close opened file
os.close( fd )

print ("Closed the file successfully!!")

执行上面代码后,将得到以下结果 -

Closed the file successfully!!

上一篇: Python os模块方法 下一篇: Python异常处理