Python3 os.write() 方法

Python3 OS 檔/目錄方法 Python3 OS 檔/目錄方法


概述

os.write() 方法用於寫入字串到檔描述符 fd 中. 返回實際寫入的字串長度。

在Unix中有效。

語法

write()方法語法格式如下:

os.write(fd, str)

參數

  • fd -- 檔描述符。

  • str -- 寫入的字串。

返回值

該方法返回寫入的實際位數。

實例

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

#!/usr/bin/python3

import os, sys

# 打開檔

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

# 寫入字串
str = "This is xuhuhu.com site"
ret = os.write(fd,bytes(str, 'UTF-8'))

# 輸入返回值

print ("寫入的位數為: ")
print (ret)

print ("寫入成功")

# 關閉檔

os.close(fd)
print ("關閉檔成功!!")

執行以上程式輸出結果為:

寫入的位數為:
23
寫入成功
關閉檔成功!!

Python3 OS 檔/目錄方法 Python3 OS 檔/目錄方法