gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
python如何判断文件或者文件夹是否存在?
- User
python如何判断文件或者文件夹是否存在?
- Assistant
可以使用os模块中的path.exists()函数,如下所示:
判断文件是否存在:
pythonimport os file_path = 'test.txt' if os.path.exists(file_path): print("找到文件啦!") else: print("没找到文件,再试试看。")判断文件夹是否存在:
pythonimport os dir_path = 'test_dir' if os.path.exists(dir_path): print("找到文件夹啦!") else: print("没找到文件夹,再试试看。")其中,os.path.exists(path)函数的返回值为True或False,表示路径path是否存在。