How can I tell if a file exists in Python?

Source: Internet
Author: User

It is usually necessary to determine whether a file or directory exists before reading or writing the file, or some processing may cause the program to fail. So it's best to determine if the file exists before doing anything. This article is for everyonedescribes three ways to determine if a file or folder exists, usingos module ,Try Statement ,pathlib Module , let's take a look at it and hope to help you learn python. 1. using the OS module Osin the moduleos.path.exists ()method is used to verify that a file exists. ·determine if a file exists ImportOsos. Path.exists (Test_file. txt) #True OS. Path.exists (No_exist_file. txt) #False ·determine if a folder exists ImportOsos. Path.exists (Test_dir) #True OS. Path.exists (No_exist_dir) #Falsecan be seen withos.path.exists ()method to determine if files and folders are the same. In fact, there is a problem with this approach, assuming you want to check the file"Test_data"exists, but there is a call in the current path"Test_data"folder, so that there may be a miscarriage of error. To avoid such a situation, it is possible to: ·Check Files only Import Osos.path.isfile ("Test-data")by this method, if the file"Test-data"does not exist will returnFalse, the reverse returnsTrue. 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 writtenUseos.access ()method to determine whether a file can read or write. Syntax: Os.access (,) Pathas the file path,Modefor operation mode, there are several: • OS. F_OK:Check if the file exists; • OS. R_OK:Check if the file is readable; • OS. W_OK:checks if a file can be written to; • OS. X_OK:checks if the file can be executedthe method returns by judging whether the file path exists and the permissions of various access modesTrueorFalse. Import OSifOs.access ("/file/path/foo.txt", OS. F_OK): Print "Given file path is exist." ifOs.access ("/file/path/foo.txt", OS. R_OK): Print "File is accessible to read" ifOs.access ("/file/path/foo.txt", OS. W_OK): Print "File is accessible to write" ifOs.access ("/file/path/foo.txt", OS. X_OK): Print "File is accessible to execute" 2. using the Try statement can be used directly in the programOpen ()method to check if the file exists and is readable and writable. Syntax: Open ()If youOpenfile does not exist, the program throws an error and uses theTrystatement to catch this error. The program cannot access the file, there may be many reasons: ·If youOpenThe file does not exist and will throw aFilenotfounderrorthe exception; ·file exists, but does not have permission to access, it throws aPersmissionerrorthe exception. so you can use the following code to determine whether a file exists: Try: F =open () F.close ()exceptFilenotfounderror: Print"File is not found."exceptPersmissionerror: Print"You don't have a permission to access this file."In fact, there is no need to deal with each exception so carefully, the above two exceptions are IOErrorsub-class. So you can simplify the program: Try: F=Open() F.Close() Except IOError: Print"File is not accessible."UseTrystatement to judge, handling all exceptions is very simple and elegant. And there is no need to introduce other external modules compared to others. 3. using the pathlib module Pathlibmodule inPython3The built-in module is in version, butPython2requires the installation of a three-party module separately. UsePathlibyou need to use the file path first to createPathobject. 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 () Source:Blog Park

How can I tell if a file exists in Python?

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.