Python os.open() 方法



Python 方法os.open()開啟指定的檔案並返回相應的 檔案描述符。它還允許我們為檔案設定各種標誌和模式。始終記住,預設模式為 0o0777(八進位制),它將檔案許可權設定為每個人都可以讀取、寫入和執行。

語法

以下是 Python os.open() 方法的語法 -

os.open(file, flags, mode, *, dir_fd);

引數

Python os.open() 方法接受以下引數 -

  • file - 要開啟的檔名。

  • flags - 以下是 flags 的選項常量。可以使用按位 OR 運算子 (|) 將它們組合在一起。並非所有平臺都提供其中的一些選項。

    • os.O_RDONLY - 只讀開啟

    • os.O_WRONLY - 只寫開啟

    • os.O_RDWR - 讀寫開啟

    • os.O_NONBLOCK - 開啟時不阻塞

    • os.O_APPEND - 每次寫入時追加

    • os.O_CREAT - 如果檔案不存在則建立檔案

    • os.O_TRUNC - 將大小截斷為 0

    • os.O_EXCL - 如果建立且檔案存在則出錯

    • os.O_SHLOCK - 原子地獲取共享鎖

    • os.O_EXLOCK - 原子地獲取排他鎖

    • os.O_DIRECT - 消除或減少快取影響

    • os.O_FSYNC - 同步寫入

    • os.O_NOFOLLOW - 不跟隨符號連結

  • mode - 此引數的工作方式與 chmod() 方法類似。

  • dir_fd - 此引數指示一個指向目錄的檔案描述符。

返回值

Python os.open() 方法返回新開啟的檔案的檔案描述符。

示例

以下示例演示了 open() 方法的使用。在這裡,我們透過提供只讀訪問許可權來開啟名為“newFile.txt”的檔案。

import os, sys

# Open a file
fd = os.open( "newFile.txt", os.O_RDONLY )

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("File contains the following string:", str)

# Close opened file
os.close( fd )
print ("File closed successfully!!")

以上程式碼將開啟一個檔案並讀取該檔案的內容 -

File contains the following string: b'Tutorialspoint'
File closed successfully!!

示例

在以下示例中,我們以讀寫許可權開啟一個檔案。如果指定的檔案不存在,則 open() 方法將建立一個同名檔案。

import os, sys

# Open a file
fd = os.open( "newFile.txt", os.O_RDWR|os.O_CREAT )

# Write one string
os.write(fd, b"This is tutorialspoint")

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("File contains the following string:")
print(str)

# Close opened file
os.close( fd )
print ("File closed successfully!!")

執行以上程式碼後,將列印以下結果 -

File contains the following string:
b'This is tutorialspoint'
File closed successfully!!
python_files_io.htm
廣告