用os.path.exists()
函数可以判断某个文件是否存在。该函数接收一个文件路径作为参数,返回一个布尔值,表示该路径对应的文件是否存在。
import os
file_path = "/path/to/file.txt"
if os.path.exists(file_path):
print("File exists.")
else:
print("File does not exist.")
上述代码中,file_path
是要检查的文件路径。os.path.exists()
函数会返回True或False,根据文件是否存在打印相应的消息。