Three ways to determine whether a file exists in Python

 

text

Usually before reading and writing a file, it is necessary to determine whether the file or directory exists, otherwise some processing methods may cause the program to fail. So it's best to check if the file exists before doing anything.

Here are three methods to determine whether a file or folder exists, using os模块, Try语句, and , respectively pathlib模块.

1. Use the os module

The methods in the os module are os.path.exists()used to check if the file exists.

  • Check if the file exists
import os
os.path.exists(test_file.txt)
#True

os.path.exists(no_exist_file.txt)
#False
  • Check if a folder exists
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 judge whether 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 there may be a misjudgment. To avoid this situation, you can do this:

  • only check files
    import os
    os.path.isfile("test-data")
    

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

Even if the file exists, you may also 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 determine whether the file can be read or written.

grammar:

os.access(path, mode)

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 if the file is writable;

  • os.X_OK: Check if the file is executable

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

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 statement

Methods can be used directly in a program open()to check if a file exists and is readable and writable.

grammar:

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 for a number of reasons:

  • If the file you open does not exist, an FileNotFoundErrorexception will be thrown;

  • 文件存在,但是没有权限访问,会抛出一个PersmissionError的异常。

所以可以使用下面的代码来判断文件是否存在:

try:
    f =open()
    f.close()
except FileNotFoundError:
    print "File is not found."
except PersmissionError:
    print "You don't have permission to access this file."

其实没有必要去这么细致的处理每个异常,上面的这两个异常都是IOError的子类。所以可以将程序简化一下:

try:
    f =open()
    f.close()
except IOError:
    print "File is not accessible."

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

3. 使用pathlib模块

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

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

  • 检查路径是否存在
path = pathlib.Path("path/file")
path.exist()
  • 检查路径是否是文件
path = pathlib.Path("path/file")
path.is_file()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324664731&siteId=291194637