Python判斷檔案/資料夾存在方法
阿新 • • 發佈:2021-07-21
四種方法:
# 第一種os.path.exists(file_path)
#第二種os.path.isfile(file_path)
#第三種pathlib模組# 第四種os.access(file_path,mode)
# 第五種 try+open() 或者with open()
示例:
import os import sys #判斷檔案是否存在 print(os.getcwd()) # vscode中 python外掛不能自動cd到當前目錄 file = os.path.join(sys.path[0],"test.txt") # 第一種 os.path.exists(file_path)print("os.path.exists method test") print(os.path.exists(file)) print(os.path.exists("test1.txt")) # 第二種 os.isfile(file_path) #這種方法判斷資料夾也是一樣的 print("os.path.isfile test") print(os.path.isfile(file)) print(os.path.isfile("test1.txt")) # 第三種 pathlib # python3.4後 內建pathlib模組 pythonp2版本需要安裝 from pathlib importPath print("pathlib test") path = Path(file) print(path.is_file()) print(path.exists()) # 第四種 os.access(file_path,mode) """ os.F_OK: 檢查檔案是否存在 0; os.R_OK: 檢查檔案是否可讀 1; os.W_OK: 檢查檔案是否可以寫入 2; os.X_OK: 檢查檔案是否可以執行 3 """ print("os.access test") print(os.access(file,0)) print(os.access("test.py",0)) # 第五種 #try + open() # with open()
執行結果:
os.path.existsmethodtest True False os.path.isfiletest True False pathlibtest True True os.accesstest True False