Python | os.pwrite 函數

怎樣寫入字節串

最近更新時間 2020-12-12 12:31:50

os.preadv 函數將 str 中的字節串 (bytestring) 寫入文件描述符 fd 的偏移位置 offset 處,保持文件偏移量不變。

偏移位置後的文件內容會被覆蓋,只會替換新字符的長度,其餘位置保持不變。

函數定義

os.pwrite(fd, str, offset)
# 函數定義

if sys.platform != 'win32':
    # Unix only
    ...
    def pwrite(__fd: int, __buffer: bytes, __offset: int) -> int: ...
    ...

兼容性:Unix 系統。

參數

  • checkfd - 文件描述符。
  • checkstr - 字節串。
  • checkoffset - 文件偏移量。

返回值

  • checkint - 寫入字符串的長度。

示例1: - 使用 os.preadv() 函數寫入字符串。

# coding=utf-8

# Python3 代碼
# 講解怎樣使用 os.pwrite() 函數寫入字符串

# 引入 os 庫
import os

# 文件路徑
path = "foo.txt"

# 使用 os.open 函數打開文件
fd = os.open(path, os.O_RDWR)

# 使用 os.pwrite 函數
# 從第 3 個位置寫入字符串
s = b"Py"
len = os.pwrite(fd, s, 3)

# 緩衝的字符長度
print('Length::', len)

# 讀取文件內容
with open(path) as f:
    print(f.read())

# 關閉文件
os.close(fd)
Length:: 2
fooPython

fd 文件描述符需要可寫權限,否則拋出 OSError 異常 OSError: [Errno 9] Bad file descriptor

rss_feed