可以使用Python中的os模块来判断文件或目录是否存在。下面是一个简单的示例代码:
import os# 判断文件是否存在file_path = 'example.txt'if os.path.exists(file_path): print(f'{file_path} 文件存在')else: print(f'{file_path} 文件不存在')# 判断目录是否存在dir_path = 'example_dir'if os.path.exists(dir_path): print(f'{dir_path} 目录存在')else: print(f'{dir_path} 目录不存在')在上面的代码中,我们首先导入os模块,然后使用os.path.exists()函数来判断文件或目录是否存在。如果文件或目录存在,函数会返回True,否则返回False。


