在Python中,你可以使用`os.path.exists()`函数来判断文件是否存在。这个函数接受一个文件路径作为参数,并返回一个布尔值,`True`表示文件存在,`False`表示文件不存在。
下面是一个简单的示例代码:
import osfile_path = "path/to/file.txt"if os.path.exists(file_path):print("文件存在")else:print("文件不存在")
如果你需要更详细的检查,比如确认文件是否为常规文件,可以使用`os.path.isfile()`函数:
import osdef is_file(file_path):try:if os.path.isfile(file_path):return Trueelse:return Falseexcept Exception as e:print(f"文件 {file_path} 存在性错误: {e}")return Falsefile_path = "example.txt"result = is_file(file_path)if result:print(f"文件 {file_path} 存在")else:print(f"文件 {file_path} 不存在")
此外,你还可以使用`pathlib`模块来进行相同的操作,如下所示:
from pathlib import Pathfile_path = Path("path/to/file.txt")if file_path.exists():print("文件存在")else:print("文件不存在")
`pathlib`是Python 3.4及以后版本引入的新模块,它提供了一个面向对象的路径处理方式,使得文件路径的操作更加直观和简洁。

