Python os.close()方法

2019-10-16 23:04:16

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!!