使用os.access()方法判斷文件是否可進(jìn)行讀寫(xiě)操作茉继。
語(yǔ)法:os.access(path, mode)
path為文件路徑坯临,mode為操作模式霍殴,有這么幾種:
os.F_OK: 檢查文件是否存在;
os.R_OK: 檢查文件是否可讀;
os.W_OK: 檢查文件是否可以寫(xiě)入;
os.X_OK: 檢查文件是否可以執(zhí)行
該方法通過(guò)判斷文件路徑是否存在和各種訪問(wèn)模式的權(quán)限返回True或者False涮帘。
import os
if os.access("/file/path/text.txt", os.F_OK):
? ? print ("Given file path is exist.")
if os.access("/file/path/text.txt", os.R_OK):
? ? print ("File is accessible to read")
if os.access("/file/path/text.txt", os.W_OK):
? ? print ("File is accessible to write")
if os.access("/file/path/text.txt", os.X_OK):
? ? print ("File is accessible to execute")