Python| os.sendfile() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
Python中的os.sendfile()
方法用于将指定数量的字节从指定的源文件描述符复制到指定的目标文件描述符,从指定的偏移量开始。
此方法返回发送的总字节数,如果达到 EOF(文件结尾),则返回 0。
Syntax: os.sendfile(dest, source, offset, count)
Parameters:
dest: A file descriptor representing destination file.
source: A file descriptor representing source file
offset: An integer value representing starting position. Bytes to be sent will be counted from this position.
count: An integer value denoting total number of bytes to be sent from source file descriptor.
Return Type: This method returns an integer value which represents the total of bytes sent from source file descriptor to dest file descriptor. 0 is returned if EOF is reached.
将以下文本视为名为'Python_intro.txt'的文件的内容。
Python is a widely-used general-purpose, high-level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently.
os.sendfile()
方法的使用# Python program to explain os.sendfile() method
# importing os module
import os
# Source file path
source = './Python_intro.txt'
# destination file path
dest = './newfile.txt'
# Open both files and get
# the file descriptor
# using os.open() method
src_fd = os.open(source, os.O_RDONLY)
dest_fd = os.open(dest, os.O_RDWR | os.O_CREAT)
# Now send n bytes from
# source file descriptor
# to destination file descriptor
# using os.sendfile() method
offset = 0
count = 100
bytesSent = os.sendfile(dest_fd, src_fd, offset, count)
print("% d bytes sent / copied successfully." % bytesSent)
# Now read the sent / copied
# content from destination
# file descriptor
os.lseek(dest_fd, 0, 0)
str = os.read(dest_fd, bytesSent)
# Print read bytes
print(str)
# Close the file descriptors
os.close(src_fd)
os.close(dest_fd)
100 bytes sent/copied successfully.
b'Python is a widely used general-purpose, high level programming language.
It was initially designed '
参考: https://docs。 Python.org/3/library/os.html#os.sendfile