Python can determine whether a file exists,

Source: Internet
Author: User

Python can determine whether a file exists,

Before reading and writing a file, you must determine whether the file or directory exists. Otherwise, some processing methods may cause errors in the program. Therefore, it is best to determine whether a file exists before performing any operations.

Here we will introduce three methods to determine whether a file or folder exists.OS Module,Try statement,Pathlib Module.

1. Use the OS Module

In the OS Moduleos.path.exists()This method is used to check whether a file exists.

  • Determine whether a file exists
import osos.path.exists(test_file.txt)#Trueos.path.exists(no_exist_file.txt)#False
  • Determine whether a folder exists
import osos.path.exists(test_dir)#Trueos.path.exists(no_exist_dir)#False

We can see thatos.path.exists()To determine whether the file and folder are the same.

In fact, this method still has a problem. Suppose you want to check whether the file "test_data" exists, but there is a folder named "test_data" in the current path, which may lead to misjudgment. To avoid this situation, you can:

  • Only check files
    import osos.path.isfile("test-data")

In this method, if the file "test-data" does not exist, False is returned, and True is returned.

That is, the file exists. You may also need to determine whether the file can be read and written.

Determine whether a file can be read/written.

Useos.access()Method to Determine whether a file can be read and written.


os.access(, )

Path is the file path and mode is the operation mode. There are several types of files:

  • OS. F_ OK: Check whether the file exists;

  • OS. R_ OK: Check whether 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 determining whether the file path exists and the permissions in various access modes.

import osif 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

Can be used directly in the programopen()To check whether the file exists and can be read and written.



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

The program may not be able to access files for many reasons:

  • If your open file does not exist,FileNotFoundError;

  • If the file exists but has no access permission,PersmissionError.

Therefore, you can use the following code to determine whether a 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."

In fact, there is no need to deal with every exception in such detail. The above two exceptions areIOError. So you can simplify the program:

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

The try statement is simple and elegant to handle all exceptions. In addition, you do not need to introduce other external modules.

3. Use the pathlib Module

The pathlib module is a built-in module in Python 3, but the third-party module needs to be installed separately in Python 2.

To use pathlib, you must first use the file path to create a path object. This path can be a file name or directory path.

  • Check whether the path exists
path = pathlib.Path("path/file")path.exist()
  • Check whether the path is a file
path = pathlib.Path("path/file")path.is_file()



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.