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


 

通常在讀寫文件之前,需要判斷文件或目錄是否存在,不然某些處理方法可能會使程序出錯。所以最好在做任何操作之前,先判斷文件是否存在。

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

1.使用os模塊

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

判斷文件是否存在

1
2
3
4
5
6
7
import  os
#如果存在返回True
>>>os.path.exists( 'test_file.txt' )
>>> True
#如果不存在返回False
>>>os.path.exists( 'no_exist_file.txt' )
>>> False

判斷文件夾是否存在

1
2
3
4
5
6
7
import  os
 
>>>os.path.exists( 'test_dir' )
>>> True
 
>>>os.path.exists( 'no_exist_dir' )
>>> False

可以看出用os.path.exists()方法,判斷文件和文件夾是一樣。

其實這種方法還是有個問題,假設你想檢查文件“test_data”是否存在,但是當前路徑下有個叫“test_data”的文件夾,這樣就可能出現誤判。為了避免這樣的情況,可以這樣:

只檢查文件

1
2
>>> import  os
>>>os.path.isfile( "test-data" )

通過這個方法,如果文件”test-data”不存在將返回False,反之返回True。

即是文件存在,你可能還需要判斷文件是否可進行讀寫操作。

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

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

語法:

1
os.access(path, mode)

path為文件路徑,mode為操作模式,有這么幾種:

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

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

  • os.W_OK: 檢查文件是否可以寫入;

  • os.X_OK: 檢查文件是否可以執行

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

1
2
3
4
5
6
7
8
9
10
11
12
>>> 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()方法來檢查文件是否存在和可讀寫。

語法:

1
open (< file / path>)

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

程序無法訪問文件,可能有很多原因:

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

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

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

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

其實沒有必要去這么細致的處理每個異常,上面的這兩個異常都是IOError的子類。所以可以將程序簡化一下:

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

使用try語句進行判斷,處理所有異常非常簡單和優雅的。而且相比其他不需要引入其他外部模塊。

3. 使用pathlib模塊  

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

使用pathlib需要先使用文件路徑來創建path對象。此路徑可以是文件名或目錄路徑。

檢查路徑是否存在

1
2
path  =  pathlib.Path( "path/file" )
path.exist()

檢查路徑是否是文件

1
2
path  =  pathlib.Path( "path/file" )
path.is_file()

判斷文件是否為空:

復制代碼
#!/usr/bin/env python
#coding:utf-8
#date:2018-04-03

import os

FILEPATH="/opt/data/report"
FILENAME="repay4.xls"
FILE=FILEPATH + os.sep + FILENAME
print(FILE)

if os.path.exists(FILE):
  print("文件存在")
  if os.path.getsize(FILE):
    print("文件存在且不為空")
    #print(os.path.getsize(FILE))
    Size=os.path.getsize(FILE)
    
    os.system('ls -lh %s' %(FILE))
  else:
    print("文件存在但為空...")   
    os.system('ls -lh %s' %(FILE))
else:
  print("文件不存在")
復制代碼

 

  

參考文檔: 

    http://www.spiderpy.cn/blog/detail/28


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM