Python os.open()方法

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!!

上一篇: Python os模組方法 下一篇: Python異常處理