當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python 3 os.write()用法及代碼示例


描述

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

相關用法


注:本文由純淨天空篩選整理自 Python 3 - os.write() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。