
整理 | Python大本营
在Python中,我们可以使用os.path.isfile()或pathlib.Path.is_file() (Python 3.4)来检查文件是否存在。1. pathlib
Python 3.4的新功能from pathlib import Path
fname = Path("c:\\test\\abc.txt")
print(fname.exists()) # true
print(fname.is_file()) # true
print(fname.is_dir()) # false
dir = Path("c:\\test\\")
print(dir.exists()) # true
print(dir.is_file()) # false
print(dir.is_dir()) # true如果检查from pathlib import Path
fname = Path("c:\\test\\abc.txt")if fname.is_file():
print("file exist!")else:
print("no such file!")2. os.path
一个经典的os.path示例。import os.path
fname = "c:\\test\\abc.txt"print(os.path.exists(fname)) # trueprint(os.path.isfile(fname)) # trueprint(os.path.isdir(fname)) # false
dir = "c:\\test\\"print(os.path.exists(dir)) # trueprint(os.path.isfile(dir)) # falseprint(os.path.isdir(dir)) # true如果检查。import os.path
fname = "c:\\test\\abc.txt"if os.path.isfile(fname):print("file exist!")else:print("no such file!")3.试试:除了
我们还可以使用try except检查文件是否存在。fname = "c:\\test\\no-such-file.txt"try:
with open(fname) as file:for line in file:print(line, end='')
except IOError as e:print(e)输出量[Errno 2] No such file or directory: 'c:\\test\\no-such-file.txt'参考文献
pathlib —面向对象的文件系统路径
os.path —常用路径名操作
博客主要介绍了Python中判断文件是否存在的方法,提及了pathlib这一面向对象的文件系统路径方式,以及os.path这一常用路径名操作方式。
1022

被折叠的 条评论
为什么被折叠?



