通常在讀寫檔案之前,需要判斷檔案或目錄是否存在,不然某些處理方法可能會使程序出錯。所以最好在做任何操作之前,先判斷檔案是否存在。
這裏將介紹三種判斷檔案或檔案夾是否存在的方法,分別使用os模組、Try語句、pathlib模組。
1、使用os模組
os模組中的ts()方法用於檢驗檔案是否存在。
判斷檔案是否存在
1
2
3
4
5
6
7
import os
#如果存在返回True
>>&ts('test_')
>>>True
#如果不存在返回False
>>&ts('no_exist_')
>>>False
判斷檔案夾是否存在
1
2
3
4
5
6
7
import os
>>&ts('test_dir')
>>>True
>>&ts('no_exist_dir')
>>>False
可以看出用ts()方法,判斷檔案和檔案夾是一樣。
其實這種方法還是有個問題,假設你想檢查檔案“test_data”是否存在,但是當前路徑下有個叫“test_data”的檔案夾,這樣就可能出現誤判。爲了避免這樣的情況,可以這樣:
只檢查檔案
1
2
>>>import os
>>&le("test-data")
透過這個方法,如果檔案”test-data”不存在將返回False,反之返回True。
即是檔案存在,你可能還需要判斷檔案是否可進行讀寫操作。
判斷檔案是否可做讀寫操作
使用ss()方法判斷檔案是否可進行讀寫操作。
語法:
1
ss(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 ss("/file/path/", os.F_OK):
>>> print "Given file path is exist."
>>>if ss("/file/path/", os.R_OK):
>>> print "File is accessible to read"
>>>if ss("/file/path/", os.W_OK):
>>> print "File is accessible to write"
>>>if ss("/file/path/", 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:
f =open()
e()
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:
f =open()
e()
except IOError:
print "File is not accessible."
使用try語句進行判斷,處理所有異常非常簡單和優雅的。而且相比其他不需要引入其他外部模組。
3、 使用pathlib模組
pathlib模組在Python3版本中是內建模組,但是在Python2中是需要單獨安裝三方模組。
使用pathlib需要先使用檔案路徑來創建path對象。此路徑可以是檔案名或目錄路徑。
檢查路徑是否存在
1
2
path = ("path/file")
t()
檢查路徑是否是檔案
1
2
path = ("path/file")
_file()
判斷檔案是否爲空:
複製代碼
複製代碼
#!/usr/bin/env python
#coding:utf-8
#date:2018-04-03
import os
FILEPATH="/opt/data/report"
FILENAME="
FILE=FILEPATH + + FILENAME
print(FILE)
if ts(FILE):
print("檔案存在")
if ize(FILE):
print("檔案存在且不爲空")
#print(ize(FILE))
Size=ize(FILE)
em('ls -lh %s' %(FILE))
else:
print("檔案存在但爲空...")
em('ls -lh %s' %(FILE))
else:
print("檔案不存在")