Python three ways to determine whether a file or folder exists

  • 2020-06-12 09:59:06
  • OfStack

You often need to determine whether a file or directory exists before you can read or write a file, or some processing may cause an error in the program. So it's best to determine if the file exists before doing anything.

There are three ways to determine whether a file or folder exists, using the os module, the Try statement, and the pathlib module.

1. Use os module

The os. path. exists() method in the os module is used to verify the existence of a file.

Determine if the file exists

import os
os.path.exists(test_file.txt)
#True
os.path.exists(no_exist_file.txt)
#False
Determine if the folder exists

import os
os.path.exists(test_dir)
#True
os.path.exists(no_exist_dir)
#False

It can be seen that os.path.exists() Method to determine if the file and folder are one.

The problem with this approach is that if you want to check for the existence of the file "test_data", but there is a folder called "test_data" in the current path, you may miscalculate. To avoid this situation, you can do this:

Check files only

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

This method returns False if the file "ES29en-ES30en" does not exist and True if not.

Even if the file exists, you may need to determine whether the file is read-write or not.

Determines whether the file can be read or written

use os.access() Method to determine whether a file can be read or written.

Grammar:


os.access(, )

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

os.F_OK: Check whether 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 if the file is executable

This method returns True or False by determining the existence of a file path and permissions for 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"

Use the Try statement

You can use the open() method directly in your program to check that a file exists and can be read or written.

Grammar:


open()

If your open file does not exist, the program will throw an error and use the try statement to catch the error.

Programs cannot access files for a number of reasons:

If your open file does not exist, an FileNotFoundError exception will be thrown. An PersmissionError exception is thrown when the file exists but has no permission to access it.

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


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

There is no need to be so meticulous with each exception; both of the above exceptions are subclasses of IOError. Therefore, the program can be simplified as follows:


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

Using the try statement for judgment, handling all exceptions is very simple and elegant. And there is no need to introduce other external modules compared to others.

3. Use pathlib module

The pathlib module is built in in Python3, but in Python2 a separate 3-side module is required.

Using pathlib requires that you first create the path object using the file path. This path can be a file name or directory path.

Check if the path exists

path = pathlib.Path("path/file")
path.exist()
Check if the path is a file

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

conclusion


Related articles: