Python判斷文件是否存在的三種方法

正文html

一般在讀寫文件以前,須要判斷文件或目錄是否存在,否則某些處理方法可能會使程序出錯。因此最好在作任何操做以前,先判斷文件是否存在。markdown

這裏將介紹三種判斷文件或文件夾是否存在的方法,分別使用os模塊Try語句pathlib模塊app


1.使用os模塊

os模塊中的os.path.exists()方法用於檢驗文件是否存在。ide

  • 判斷文件是否存在
1 import os 2 os.path.exists(test_file.txt) 3 #True
4 
5 os.path.exists(no_exist_file.txt) 6 #False

 

  • 判斷文件夾是否存在
1 import os 2 os.path.exists(test_dir) 3 #True
4 
5 os.path.exists(no_exist_dir) 6 #False

 

能夠看出用os.path.exists()方法,判斷文件和文件夾是同樣。this

其實這種方法仍是有個問題,假設你想檢查文件「test_data」是否存在,可是當前路徑下有個叫「test_data」的文件夾,這樣就可能出現誤判。爲了不這樣的狀況,能夠這樣:spa

  • 只檢查文件
    1 import os 2 os.path.isfile("test-data")

     

經過這個方法,若是文件」test-data」不存在將返回False,反之返回True。code

便是文件存在,你可能還須要判斷文件是否可進行讀寫操做。htm

 

判斷文件是否可作讀寫操做

使用os.access()方法判斷文件是否可進行讀寫操做。對象

語法:blog

os.access(path, mode)

path爲文件路徑,mode爲操做模式,有這麼幾種:

  • os.F_OK: 檢查文件是否存在;

  • os.R_OK: 檢查文件是否可讀;

  • os.W_OK: 檢查文件是否能夠寫入;

  • os.X_OK: 檢查文件是否能夠執行

該方法經過判斷文件路徑是否存在和各類訪問模式的權限返回True或者False。

 1 import os  2 if os.access("/file/path/foo.txt", os.F_OK):  3     print "Given file path is exist."
 4 
 5 if os.access("/file/path/foo.txt", os.R_OK):  6     print "File is accessible to read"
 7 
 8 if os.access("/file/path/foo.txt", os.W_OK):  9     print "File is accessible to write"
10 
11 if os.access("/file/path/foo.txt", os.X_OK): 12     print "File is accessible to execute"

 

 

2.使用Try語句

能夠在程序中直接使用open()方法來檢查文件是否存在和可讀寫。

語法:

open()

若是你open的文件不存在,程序會拋出錯誤,使用try語句來捕獲這個錯誤。

程序沒法訪問文件,可能有不少緣由:

  • 若是你open的文件不存在,將拋出一個FileNotFoundError的異常;

  • 文件存在,可是沒有權限訪問,會拋出一個PersmissionError的異常。

因此可使用下面的代碼來判斷文件是否存在:

1 try: 2     f =open() 3  f.close() 4 except FileNotFoundError: 5     print "File is not found."
6 except PersmissionError: 7     print "You don't have permission to access this file."

 

其實沒有必要去這麼細緻的處理每一個異常,上面的這兩個異常都是IOError的子類。因此能夠將程序簡化一下:

1 try: 2     f =open() 3  f.close() 4 except IOError: 5     print "File is not accessible."

 

使用try語句進行判斷,處理全部異常很是簡單和優雅的。並且相比其餘不須要引入其餘外部模塊。

 

3. 使用pathlib模塊

pathlib模塊在Python3版本中是內建模塊,可是在Python2中是須要單獨安裝三方模塊。

使用pathlib須要先使用文件路徑來建立path對象。此路徑能夠是文件名或目錄路徑。

  • 檢查路徑是否存在
1 path = pathlib.Path("path/file") 2 path.exist()

 

  • 檢查路徑是不是文件
1 path = pathlib.Path("path/file") 2 path.is_file()

 

 

博客原文:http://www.spiderpy.cn/blog/detail/28

相關文章
相關標籤/搜索