python-----判斷文件是否存在


判斷文件是否存在有三種方法:分別使用 os模塊Try語句pathlib模塊

方法一:使用 os模塊:

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

# 判斷文件/文件夾是否存在,存在返回True,不存在返回False
import os
os.path.exists(test_file.jpg)
os.path.exists(test_dir)
#True
os.path.exists(not_exist_file.jpg)
os.path.exists(not_exist_dir)
#False

判斷文件是否存在還可以使用 os.path.isfile():

import os
test_file_path = r'F:\temp\1.jpg'
os.path.isfile(test_file_path)
#True

如果存在且是文件就返回True,如果不存在,或存在但不是文件就返回Flase

 

方法二:使用try語句:

test_file_path = r'F:\temp\2.jpg'
try:
    f =open(test_file_path)
    f.close()
except Exception as e:
    print("File is not accessible.",e)

此方法如果文件不存在,即無法打開文件,會拋出異常

 

方法三:使用pathlib

import pathlib
# 使用pathlib需要先使用文件路徑來創建path對象。此路徑可以是文件名或目錄路徑。
# 檢查路徑是否存在
test_file_path = r'F:\temp\1.jpg'
path = pathlib.Path(test_file_path)
path.exists()     #判斷文件或文件夾是否存在
path.is_file()    #判斷是否是文件

如果存在返回True,不存在返回Flase

如果是文件返回True,不是文件則返回Flase

 

 

 

博客原文:https://www.cnblogs.com/jhao/p/7243043.html#_label0

 


免責聲明!

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



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