Python中的OS模块提供了与操作系统进行交互的函数。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的函数的便携式方法。
os.pwrite()
Python中的方法用于将指定的字节字符串写入与指定位置的指定文件描述符关联的文件。任何现有值都将在指定位置被覆盖。
文件描述符是一个小整数值,对应于当前进程已打开的文件。它用于执行各种较低级别的I /O操作,例如读取,写入,发送等。
注意:os.pwrite()
方法旨在用于低级操作,并且应应用于由返回的文件描述符os.open()
或者os.pipe()
方法。
用法: os.pwrite(fd, str, offset)
参数:
fd:表示要写入文件的文件描述符。
str:一个字节字符串,表示要写入文件的内容
offset:表示起始位置的整数。文件写入将从该偏移值开始。
返回类型:此方法返回一个整数值,表示实际写入的字节数。 。
将以下文本视为名为file.txt的文件的内容。
C, C++, Java, C#, PHP
代码:os.pwrite()方法的使用
# Python program to explain os.pwrite() method
# Importing os module
import os
# Filename
filename = "file.txt"
# Open the file and get the
# file descriptor associated
# with it using os.open method
fd = os.open(filename, os.O_RDWR)
# String to be written in the file
s = "Python, "
# converting string to bytestring
text = s.encode("utf-8")
# Position from where
# file writing will start
offset = 0
# As offset is 0, bytestring
# will be written in the
# beginning of the file
# Write the bytestring
# to the file indicated by
# file descriptor at
# specified position
bytesWritten = os.pwrite(fd, text, offset)
print("Number of bytes actually written:", bytesWritten)
# Print the content of the file
with open(filename) as f:
print(f.read())
# String to be written in the file
s = "Javascript, "
# converting string to bytestring
text = s.encode("utf-8")
# Position from where
# file writing will start
# os.stat(fd).st_size will return
# file size in bytes
# so bytestring will be written
# at the end of the file
offset = os.stat(fd).st_size
# Write the bytestring
# to the file indicated by
# file descriptor at
# specified position
bytesWritten = os.pwrite(fd, text, offset)
print("\nNumber of bytes actually written:", bytesWritten)
# Print the content of the file
with open(filename) as f:
print(f.read())
# String to be written in the file
s = "R Programming, "
# converting string to bytestring
text = s.encode("utf-8")
# Position from where
# file writing will start
offset = 10
# Write the bytestring
# to the file indicated by
# file descriptor at
# specified position
bytesWritten = os.pwrite(fd, text, offset)
print("\nNumber of bytes actually written:", bytesWritten)
# Print the content of the file
with open(filename) as f:
print(f.read())
输出:
Number of bytes actually written:8 Python, Java, C#, PHP Number of bytes actually written:12 Python, Java, C#, PHP Javascript, Number of bytes actually written:15 Python, JaR Programming, ascript,
相关用法
- Python next()用法及代码示例
- Python os.dup()用法及代码示例
- Python set()用法及代码示例
- Python Decimal max()用法及代码示例
- Python PIL ImageOps.fit()用法及代码示例
- Python os.rmdir()用法及代码示例
- Python sympy.det()用法及代码示例
- Python Decimal min()用法及代码示例
- Python os.readlink()用法及代码示例
- Python os.writev()用法及代码示例
- Python os.readv()用法及代码示例
- Python PIL RankFilter()用法及代码示例
- Python os.rename()用法及代码示例
- Python os.sendfile()用法及代码示例
注:本文由纯净天空筛选整理自ihritik大神的英文原创作品 Python | os.pwrite() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。