Python os.open()方法

2019-10-16 23:04:50

Python的open()方法開啟檔案,根據標誌和可能的模式設定各種標誌。預設模式為0777(八進位制),當前umask值首先被遮蔽。

語法

以下是open()方法的語法 -

os.open(file, flags[, mode]);

引數

  • filename - 要開啟的檔案名。
  • mode - 這個工作方式與chmod()方法相似。
  • 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 - 不要遵循符號連結

返回值

  • 此方法返回新開啟的檔案的檔案描述符。

範例

以下範例顯示了open()方法的用法。

#!/usr/bin/python3
import os, sys

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

# Write one string

line = "this is test" 
# string needs to be converted byte object
b = str.encode(line)
os.write(fd, b)

# Close opened file
os.close( fd)

print ("Closed the file successfully!!")

執行上面程式碼,這將建立給定的檔案foo.txt,然後將在該檔案中寫入給定的內容,並產生以下結果 -

Closed the file successfully!!