描述
方法open()打開文件文件,根據flags設置各種flags,可能還根據mode設置它的mode。默認的mode是0777(八進製),首先屏蔽掉當前的umask值。
用法
以下是語法open()方法 -
os.open(file, flags[, mode]);
參數
file− 要打開的文件名。
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() 方法的用法方式類似。
返回值
此方法返回新打開文件的文件描述符。
示例
下麵的例子展示了 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 3 os.openpty()用法及代碼示例
- Python 3 os.fstatvfs()用法及代碼示例
- Python 3 os.minor()用法及代碼示例
- Python 3 os.close()用法及代碼示例
- Python 3 os.unlink()用法及代碼示例
- Python 3 os.major()用法及代碼示例
- Python 3 os.rmdir()用法及代碼示例
- Python 3 os.fdopen()用法及代碼示例
- Python 3 os.fdatasync()用法及代碼示例
- Python 3 os.isatty()用法及代碼示例
- Python 3 os.rename()用法及代碼示例
- Python 3 os.walk()用法及代碼示例
- Python 3 os.renames()用法及代碼示例
- Python 3 os.makedirs()用法及代碼示例
- Python 3 os.utime()用法及代碼示例
- Python 3 os.tcgetpgrp()用法及代碼示例
- Python 3 os.statvfs()用法及代碼示例
- Python 3 os.lchown()用法及代碼示例
- Python 3 os.mknod()用法及代碼示例
- Python 3 os.lstat()用法及代碼示例
注:本文由純淨天空篩選整理自 Python 3 - os.open() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。