Python 如何检查某文件是否存在

在 Python 3.4 之前, 我们几乎只有一种方法,就是用 os.path.isfile()
来检查某文件是否存在;从 Python 3.4 以后,我们可以用 pathlib
模块里面的面向对象的方法来检查文件是否存在。
os.path.isfile()
import os
fileName = "temp.txt"
os.path.isfile(fileName)
它检查了文件 fileName
是否存在。
一些人更喜欢用来 os.path.exists()
检查文件是否存在。但它无法区分检查对象是文件还是目录。
import os
fileName = "temp.txt"
print(os.path.exists(fileName))
fileName = r"C:\Test"
print(os.path.exists(fileName))
因此,如果你想检查文件是否存在,只使用 os.path.isfile
函数。
pathlib.Path.is_file()
从 Python 3.4 开始,我们有了 pathlib
模块里面的面向对象的方法来检查文件是否存在。
from pathlib import Path
fileName = "temp.txt"
fileObj = Path(fileName)
print(fileObj.is_file())
类似的,该模块还有 is_dir()
和 exists
方法来检查文件夹,文件/文件夹是否存在。
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn