Three methods for Python to determine whether a file or folder exists

It is often necessary to determine whether the file or directory exists before reading or writing a file, otherwise some processing methods may make the program error. Therefore, it is best to determine whether the file exists before doing the operation.

Here will introduce three methods to determine whether a file or folder exists, using the os module, Try statement, and pathlib module respectively.

1. Use the os module

The os.path.exists() method in the os module is used to check whether the file exists.

  • Determine whether the file exists

1

2

3

4

5

import os

os.path.exists(test_file.txt)

#True

os.path.exists(no_exist_file.txt)

#False

  • Determine whether the folder exists

1

2

3

4

5

import os

os.path.exists(test_dir)

#True

os.path.exists(no_exist_dir)

#False

It can be seen that the os.path.exists()method is used to determine that the file and the folder are the same.

In fact, there is still a problem with this method. Suppose you want to check whether the file "test_data" exists, but there is a folder called "test_data" in the current path, so a misjudgment may occur. To avoid this situation, you can do this:

  • Only check files

1

2

import os

os.path.isfile("test-data")

With this method, if the file "test-data" does not exist, it will return False, otherwise it will return True.

Even if the file exists, you may need to determine whether the file can be read or written.

Determine whether the file can be read and written

Use os.access()method to judge whether the file can be read and written.

grammar:

1

os.access(, )

path is the file path, mode is the operation mode, there are several types:

  • os.F_OK: Check if the file exists;
  • os.R_OK: Check if the file is readable;
  • os.W_OK: Check whether the file can be written;
  • os.X_OK: Check whether the file can be executed

This method returns True or False by judging whether the file path exists and the permissions of various access modes.

1

2

3

4

5

6

7

8

9

import os

if os.access("/file/path/foo.txt", os.F_OK):

  print "Given file path is exist."

if os.access("/file/path/foo.txt", os.R_OK):

  print "File is accessible to read"

if os.access("/file/path/foo.txt", os.W_OK):

  print "File is accessible to write"

if os.access("/file/path/foo.txt", os.X_OK):

  print "File is accessible to execute"

2. Use the Try open statement

You can directly use the open() method in the program to check whether the file exists and is readable and writable.

grammar:

1

open()

If the file you open does not exist, the program will throw an error. Use the try statement to catch this error.

The program cannot access the file, there may be many reasons:

  • If the file you open does not exist, a FileNotFoundError exception will be thrown;
  • If the file exists but does not have permission to access, a PersmissionError will be thrown.

So you can use the following code to determine whether the file exists:

1

2

3

4

5

6

7

try:

  f =open()

  f.close()

except FileNotFoundError:

  print "File is not found."

except PersmissionError:

  print "You don't have permission to access this file."

In fact, there is no need to handle each exception in such a detailed manner. The two exceptions above are subclasses of IOError. So the procedure can be simplified a bit:

1

2

3

4

5

try:

  f =open()

  f.close()

except IOError:

  print "File is not accessible."

使用try语句进行判断,处理所有异常非常简单和优雅的。而且相比其他不需要引入其他外部模块。

3. 使用pathlib模块

pathlib模块在Python3版本中是内建模块,但是在Python2中是需要单独安装三方模块。

使用pathlib需要先使用文件路径来创建path对象。此路径可以是文件名或目录路径。

  • 检查路径是否存在

1

2

path = pathlib.Path("path/file")

path.exist()

  • 检查路径是否是文件

1

2

path = pathlib.Path("path/file")

path.is_file()

Guess you like

Origin blog.csdn.net/u012308586/article/details/108370395