Python os.write() 方法



Python 的 write() 方法(OS 模組)用於以位元組形式寫入字串。返回寫入的位元組數。

此方法將位元組字串寫入由 "os.open()" 或 "os.pipe()" 方法返回的給定檔案描述符。我們能否向檔案寫入內容取決於它開啟的模式。

語法

Python os.write() 方法的語法如下:

os.write(fd, str)

引數

Python os.write() 方法接受以下引數:

  • fd − 這是表示目標檔案的檔案描述符。

  • str − 此引數指定要寫入的字串。

返回值

Python os.write() 方法返回寫入的位元組數。

示例

以下示例演示了 Python os.write() 方法的使用。在這裡,我們以讀寫模式開啟一個檔案並檢查寫入的位元組數。

import os, sys

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

# Writing text
ret = os.write(fd, b"Writing a demo text...")

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

print ("written successfully")

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

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

the number of bytes written: 
22
written successfully
file closed successfully!!
python_files_io.htm
廣告