Python | os.sendfile 函數
怎樣根據文件描述符複製文件內容
最近更新時間 2020-12-16 14:17:37
os.sendfile 函數將文件描述符 in_fd 中的 count 字節複製到文件描述符 out_fd 的偏移位置 offset 處。返回複製的字節數,如果到達 EOF,返回 0。
支持將套接字作為 out_fd 文件描述符。Mac OS X 和 FreeBSD 系統中可以使用 headers 等參數。
函數定義
    os.sendfile(out_fd, in_fd, offset, count)
  
  # 函數定義
if sys.platform != 'win32':
    # Unix only
    ...
    @overload
    def sendfile(__out_fd: int, __in_fd: int, offset: Optional[int], count: int) -> int: ...
    @overload
    def sendfile(
        __out_fd: int,
        __in_fd: int,
        offset: int,
        count: int,
        headers: Sequence[bytes] = ...,
        trailers: Sequence[bytes] = ...,
        flags: int = ...,
    ) -> int: ...  # FreeBSD and Mac OS X only
    ...
  兼容性:Unix 系統。
參數
- checkout_fd - 目標文件描述符。
 - checkin_fd - 源文件描述符。
 - checkoffset - 文件偏移量。
 - checkcount - 複製的字節長度。
 
返回值
- checkint - 複製的字節長度,在文件尾可能小於 count。
 
示例1: - 使用 os.sendfile() 函數複製文件數據。
# coding=utf-8
# Python3 代碼
# 講解怎樣使用 os.sendfile() 函數複製文件數據
# 引入 os 模塊
import os
# 源文件路徑
path = "foo.txt"
# 輸出文件路徑
out_path = "out.txt"
# 使用 os.open 函數打開文件
# 源文件只需要讀權限
in_fd = os.open(path, os.O_RDONLY)
# 輸出文件需要讀寫權限
# 最好加上 CREATE 權限,否則文件不存在會報錯
out_fd = os.open(out_path, os.O_RDWR|os.O_CREAT)
# 使用 os.sendfile 函數
# 發送 3 字節數據
offset = 0
count = 3
ret_val = os.sendfile(out_fd, in_fd, offset, count)
print("Send Btyes::", ret_val)
# 關閉文件
os.close(in_fd)
os.close(out_fd)
  Send Btyes:: 3
注意:文件如果使用 UTF-8 編碼,中文為 3個字節,如果複製不是 3的倍數,可能會產生亂碼。