Python | os.open 函數

怎樣使用系統級函數打開文件

最近更新時間 2020-12-10 14:05:21

os.open 函數根據 path 路徑 和 flags 標誌位打開文件,並根據 mode 設置其權限狀態。當計算 mode 時,會首先根據當前 umask 值將部分權限去除。本方法返回新文件的描述符。新的文件描述符不可繼承。

flag 和 mode 參數說明參見函數定義,常用標誌位(如 O_RDONLY 和 O_WRONLY)。在 Windows 上需要添加 O_BINARY 才能以二進制模式打開文件。

本函數適用於底層的 I/O 操作。常規用途請使用內置函數 open(),該函數的 read() 和 write() 方法(及其他方法)會返回 文件對象。要將文件描述符包裝在文件對象中,請使用 fdopen()。

函數定義

os.open(path, flags, mode=0o777, *, dir_fd=None)
# 函數定義

def open(file: _PathType, flags: int, mode: int = ..., *, dir_fd: Optional[int] = ...) -> int: ...

# 標誌位常量定義
O_RDONLY: int # os.O_RDONLY::0::0x0
O_WRONLY: int # os.O_WRONLY::1::0x1
O_RDWR: int # os.O_RDWR  ::2::0x10
O_APPEND: int # os.O_APPEND::1024::0x10000000000
O_CREAT: int # os.O_CREAT ::64::0x1000000
O_EXCL: int # os.O_EXCL  ::128::0x10000000
O_TRUNC: int # os.O_TRUNC ::512::0x1000000000

O_DSYNC: int    # Unix only
O_RSYNC: int    # Unix only
O_SYNC: int     # Unix only
O_NDELAY: int   # Unix only
O_NONBLOCK: int  # Unix only
O_NOCTTY: int   # Unix only
O_CLOEXEC: int  # Unix only
O_SHLOCK: int   # Unix only
O_EXLOCK: int   # Unix only

O_BINARY: int     # Windows only
O_NOINHERIT: int  # Windows only
O_SHORT_LIVED: int  # Windows only
O_TEMPORARY: int  # Windows only
O_RANDOM: int     # Windows only
O_SEQUENTIAL: int  # Windows only
O_TEXT: int       # Windows only

O_ASYNC: int      # Gnu extension if in C library
O_DIRECT: int     # Gnu extension if in C library
O_DIRECTORY: int  # Gnu extension if in C library
O_NOFOLLOW: int   # Gnu extension if in C library
O_NOATIME: int    # Gnu extension if in C library
O_PATH: int  # Gnu extension if in C library
O_TMPFILE: int  # Gnu extension if in C library
O_LARGEFILE: int  # Gnu extension if in C library

參數

  • checkpath - 文件路徑。
  • checkflags - 操作標誌位,詳細參數參見函數定義。
  • checkmode - [可選參數],默認為 0o777。

返回值

  • checkint - 文件描述符。

示例1: - 使用 os.open() 函數打開文件。

# coding=utf-8

# Python3 代碼
# 講解怎樣使用 os.open() 函數打開文件

# 引入 os 庫
import os

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

# 權限,可選、八進制
mode = 0o666

# 標誌位
flags = os.O_RDWR | os.O_CREAT

# 使用 os.open 函數獲取文件描述符
fd = os.open(path, flags, mode)
print("File path opened successfully.") 

# 關閉文件
os.close(fd)
File path opened successfully.
rss_feed