Python| os.write() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
Python中的os.write()
方法用于将字节串写入给定的文件描述符。
文件描述符是与当前进程已打开的文件相对应的小整数值。它用于执行各种较低级别的 I/O 操作,如读、写、发送等。
注意: os.write()
方法用于低级操作,应应用于os.open()
或os.pipe()
方法返回的文件描述符。
Syntax: os.write(fd, str)
Parameter:
fd: The file descriptor representing the target file.
str: A bytes-like object to be written in the file.
Return Type: This method returns an integer value which represents the number of bytes actually written.
代码:使用 os.write() 方法将字节串写入给定的文件描述符
# Python program to explain os.write() method
# importing os module
import os
# File path
path = "/home / ihritik / Documents / GeeksForGeeks.txt"
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_RDWR)
# String to be written
s = "GeeksForGeeks: A Computer science portal for Geeks."
# Convert the string to bytes
line = str.encode(s)
# Write the bytestring to the file
# associated with the file
# descriptor fd and get the number of
# Bytes actually written
numBytes = os.write(fd, line)
print("Number of bytes written:", numBytes)
# close the file descriptor
os.close(fd)
输出:
Number of bytes written: 51