os.write() 方法



描述

write() 方法將字串 str 寫入檔案描述符 fd。它返回實際寫入的位元組數。

語法

以下是 write() 方法的語法:

os.write(fd, str)

引數

  • fd − 這是檔案描述符。

  • str − 這是要寫入的字串。

返回值

此方法返回實際寫入的位元組數。

示例

以下示例演示了 write() 方法的用法:

import os, sys

# Open a file
fd = os.open( "f1.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)
ret=os.write(fd, b)

# ret consists of number of bytes written to f1.txt
print ("the number of bytes written: ", ret)

# Close opened file
os.close( fd)
print ("Closed the file successfully!!")

執行上述程式時,會產生以下結果:

the number of bytes written: 12
Closed the file successfully!!
python_os_file_directory_methods.htm
廣告