Python3 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!!

上一篇: Python3文件方法 下一篇: Python3 os文件目录的方法