Python uses three methods to determine if a file or folder exists for instance sharing

Source: Internet
Author: User
This article introduces three kinds of methods for judging whether files or folders exist, using OS module, try statement, Pathlib module respectively. Interested friends to see it together

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

Here are three ways to determine if a file or folder exists, using OS module, try statement, Pathlib module, respectively.

1. Using the OS module

The Os.path.exists () method in the OS module is used to verify that the file exists.

    • Determine if a file exists


Import osos.path.exists (Test_file.txt) #Trueos. Path.exists (no_exist_file.txt) #False
    • Determine if a folder exists


Import osos.path.exists (Test_dir) #Trueos. Path.exists (No_exist_dir) #False

You can see os.path.exists() how the File and folder are the same.

In fact, there is a problem with this approach, assuming you want to check whether the file "Test_data" exists, but there is a folder called "Test_data" under the current path, so there may be a miscarriage of error. To avoid such a situation, you can:

    • Check Files only


Import Osos.path.isfile ("Test-data")

By this method, if the file "Test-data" does not exist, it will return false, and vice versa returns True.

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

Determine if a file can be read or written

Use os.access() the method to determine whether a file can read or write.

Grammar:


Os.access (,)

Path is the file path, mode is the operating pattern, there are several:

    • 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: Checks if the file can be executed

The method returns TRUE or false by judging whether the file path exists and the permissions of the 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. Using the Try Statement

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

Grammar:


Open ()

If your open file does not exist, the program throws an error and uses a try statement to catch the error.

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

    • If you open the file does not exist, will throw a Filenotfounderror exception;

    • The file exists, but does not have permission to access it, and throws an Persmissionerror exception.

So 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" has permission to access the this file. "

In fact, there is no need to deal with each exception in such detail, the above two exceptions are ioerror subclasses. So you can simplify the program:


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

It is very simple and elegant to handle all exceptions using the Try statement. And there is no need to introduce other external modules compared to others.

3. Using the Pathlib module

The Pathlib module is a built-in module in the Python3 version, but in Python2 it is necessary to install the three-party module separately.

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

    • Check if path exists


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


Path = Pathlib. Path ("Path/file") Path.is_file ()

Summarize

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: info-contact@alibabacloud.com 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.