Python | 检查文件是否存在?

任务是检查文件是否存在

在继续本教程之前,请注意–有一些单独的功能可用于检查文件或目录是否存在。因此,您必须确定要检查文件或目录的内容。

要使用这些功能,我们必须导入“ os”模块,这些功能是:

  1. os。path.isfile():检查文件是否存在。

  2. os。path.isdir():检查目录是否存在。

  3. os。path.exists():检查文件或目录。

因此,如果不确定文件或目录,我建议使用“ os。”path.exists()函数来避免该错误。

示例

在此示例中,我们正在检查文件“ file.txt”,如果该文件不存在,我们将创建并关闭该文件,然后再次检查同一文件。

# 进口声明
import os

# 检查文件
if not(os.path.exists("file.txt")):
	print("File does not exist")
	# creating & closing file 
	fo = open("file.txt","wt")
	fo.close();
else:
	print("File exists")

# 再次检查
if os.path.exists("file.txt"):
	print("Now, file exists")
else:
	print("File does not exist")

输出结果

File does not exist
Now, file exists