![66e51542467cfd65f60377ad0e23225d.gif](https://i-blog.csdnimg.cn/blog_migrate/3e8ab73f00da45cde942470a7ec690ac.gif)
整理 | 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 —常用路径名操作