在Python中,你可以使用os模块的path.exists()函数来检查一个文件是否存在。以下是一个简单的例子:
import os # 文件路径
file_path = '/path/to/your/file.txt' # 检查文件是否存在
if os.path.exists(file_path): print(f"文件 {file_path} 存在。")
else: print(f"文件 {file_path} 不存在。")
在这个例子中,你需要将/path/to/your/file.txt替换为你要检查的文件的实际路径。如果文件存在,os.path.exists(file_path)将返回True,否则返回False。
注意:os.path.exists()函数不仅可以检查文件是否存在,还可以检查目录是否存在。如果你只想检查文件是否存在(而不是目录),你可以使用os.path.isfile()函数:
import os # 文件路径
file_path = '/path/to/your/file.txt' # 检查文件是否存在
if os.path.isfile(file_path): print(f"文件 {file_path} 存在。")
else: print(f"文件 {file_path} 不存在。")
在这个例子中,os.path.isfile(file_path)将只在file_path指向一个实际文件时返回True。如果file_path指向一个目录或其他类型的文件系统条目(如设备、套接字等),它将返回False。