通常在讀寫檔之前, 需要判斷檔或目錄是否存在, 不然某些處理方法可能會使程式出錯。 所以最好在做任何操作之前, 先判斷檔是否存在。
這裡將介紹三種判斷檔或資料夾是否存在的方法, 分別使用os模組、Try語句、pathlib模組。
1.使用os模組
os模組中的os.path.exists方法用於檢驗檔是否存在。
判斷檔是否存在import os os.path.exists(test_file.txt) #True os.path.exists(no_exist_file.txt) #False 判斷資料夾是否存在import os os.path.exists(test_dir) #True os.path.exists(no_exist_dir) #False可以看出用os.path.exists方法, 判斷檔和資料夾是一樣。
其實這種方法還是有個問題, 假設你想檢查檔“test_data”是否存在, 但是當前路徑下有個叫“test_data”的資料夾, 這樣就可能出現誤判。 為了避免這樣的情況, 可以這樣:
只檢查檔 import os os.path.isfile("test-data")通過這個方法,
即是檔存在, 你可能還需要判斷檔是否可進行讀寫操作。
判斷檔是否可做讀寫操作
使用os.access方法判斷檔是否可進行讀寫操作。
語法:
os.access(, )
path為檔路徑, mode為操作模式, 有這麼幾種:
os.F_OK: 檢查檔是否存在;
os.R_OK: 檢查檔是否可讀;
os.W_OK: 檢查檔是否可以寫入;
os.X_OK: 檢查檔是否可以執行
該方法通過判斷檔路徑是否存在和各種訪問模式的許可權返回True或者False。
import os if os.access("/file/path/foo.txt", os.F_OK): print "Given file path is exist." if os.access("/file/path/foo.txt", os.R_OK): print "File is accessible to read" if os.access("/file/path/foo.txt", os.W_OK): print "File is accessible to write" if os.access("/file/path/foo.txt", os.X_OK): print "File is accessible to execute"2.使用Try語句
可以在程式中直接使用open方法來檢查檔是否存在和可讀寫。
語法:
open
如果你open的檔不存在, 程式會拋出錯誤, 使用try語句來捕獲這個錯誤。
程式無法訪問檔, 可能有很多原因:
如果你open的檔不存在, 將拋出一個FileNotFoundError的異常;
檔存在, 但是沒有許可權訪問, 會拋出一個PersmissionError的異常。
所以可以使用下面的代碼來判斷檔是否存在:
try: f =open f.close except FileNotFoundError: print "File is not found." except PersmissionError: print "You don't have permission to access this file."其實沒有必要去這麼細緻的處理每個異常, 上面的這兩個異常都是IOError的子類。 所以可以將程式簡化一下:
try: f =open f.close except IOError: print "File is not accessible."使用try語句進行判斷, 處理所有異常非常簡單和優雅的。 而且相比其他不需要引入其他外部模組。
3. 使用pathlib模組
pathlib模組在Python3版本中是內建模組, 但是在Python2中是需要單獨安裝三方模組。
使用pathlib需要先使用檔路徑來創建path物件。 此路徑可以是檔案名或目錄路徑。
檢查路徑是否存在path = pathlib.Path("path/file") path.exist 檢查路徑是否是檔path = pathlib.Path("path/file") path.is_file博客原文:http://www.spiderpy.cn/blog/detail/28