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

 

posted @ 2019-01-19 15:30  小呆丶  阅读(7050)  评论(0编辑  收藏  举报