天天看点

Python | 检查文件是否存在?

The task is to

check whether a file exists or not

?

任务是

检查文件是否存在

Before continuing to the tutorial, please note that – there are some of the separate functions which are used to

check whether a file or directory exists or not

. So you have to make sure what you want to check a file or a directory.

在继续学习本教程之前,请注意–有一些单独的函数用于

检查文件或目录是否存在

。 因此,您必须确定要检查文件或目录的内容。

To use the functions, we have to import the

"os"

module, the functions are:

要使用这些功能,我们必须导入

“ os”

模块,这些功能是:

  1. os.path.isfile() : To check whether a file exists or not. os.path.isfile() :检查文件是否存在。
  2. os.path.isdir() : To check whether a directory exists or not. os.path.isdir() :检查目录是否存在。
  3. os.path.exists() : To check for both either a file or a directory. os.path.exists() :检查文件还是目录。

So, if you are not sure about the file or directory, I would recommend using

"os.path.exists()"

function to avoid the error.

因此,如果不确定文件或目录,建议使用

“ os.path.exists()”

函数来避免该错误。

Example: 例:

In this example, we are checking a file

"file.txt"

and if it does not exist, we will create and close the file and then again check for the same file.

在此示例中,我们正在检查文件

“ file.txt”

,如果该文件不存在,则将创建并关闭该文件,然后再次检查同一文件。

# import statement
import os

# checking file
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")

# checking again
if os.path.exists("file.txt"):
	print("Now, file exists")
else:
	print("File does not exist")
           
Output 输出量
File does not exist
Now, file exists
           
翻译自: https://www.includehelp.com/python/check-if-a-file-exists-or-not.aspx