open()方法根據標記(flags),並根據設置各種標誌在指定模式下打開檔。缺省模式為0777(八進制),當前的 umask 值首先遮罩。
語法
以下是open()方法的語法:
os.open(file, flags[, mode]);
參數
-
file -- 要打開的檔案名
-
flags -- 以下常量是標誌 flags 選項。可以用位或操作符相結合。但是其中有些是不是適用於所有平臺。
- 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() 方法工作的方式類似
返回值
此方法返回新打開檔的檔描述符。
示例
下麵的示例顯示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!!
上一篇:
Python3檔方法
下一篇:
Python3 os檔目錄的方法