Python os.write()方法

2019-10-16 23:05:20

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

語法

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

os.write(fd, str)

引數

  • fd - 這是檔案描述符。
  • str - 這是要寫的字串。

返回值

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

範例

以下範例顯示了write()方法的用法。

# !/usr/bin/python3
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!!