1. Use os modular
2. Use Try sentence
3. Use pathlib modular
Usually before reading and writing files , You need to judge whether the file or directory exists , Otherwise, some processing methods may make the program error . So it's best to do anything before , First, judge whether the file exists .
Here are three ways to determine whether a file or folder exists , Separate use os modular 、Try sentence 、pathlib modular .
1. Use os modularos Module os.path.exists() Method is used to verify the existence of a file .
Judge whether the file exists
import osos.path.exists(test_file.txt)#Trueos.path.exists(no_exist_file.txt)#False
Determine whether the folder exists
import osos.path.exists(test_dir)#Trueos.path.exists(no_exist_dir)#False
It can be seen that os.path.exists() Method , Judge whether files and folders are the same .
In fact, there is still a problem with this method , Suppose you want to check the file “test_data” Whether there is , But there is a name under the current path “test_data” Folder , In this way, misjudgment may occur . To avoid such a situation , It can be like this :
Check only files
import osos.path.isfile("test-data")
Through this method , If the file ”test-data” Does not exist, will return False, Instead, return to True.
That is, the file exists , You may also need to determine whether the file can be read and written .
Judge whether the file can be read or written
Use os.access() Method to determine whether the file can be read and written .
grammar :
os.access(path, mode)
path Is the file path ,mode Is the operation mode , There are so many :
os.F_OK: Check if the file exists ;
os.R_OK: Check that the file is readable ;
os.W_OK: Check whether the file can be written ;
os.X_OK: Check if the file can be executed
This method returns by judging whether the file path exists and the permissions of various access modes True perhaps False.
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 Try sentence It can be used directly in the program open() Method to check whether the file exists and can be read and written .
grammar :
open()
If you open The file for does not exist , The program will throw an error , Use try Statement to catch this error .
The program cannot access the file , There may be many reasons :
If you open The file for does not exist , Will throw a FileNotFoundError It's abnormal ;
File exists , But you don't have access to , Will throw out a PersmissionError It's abnormal .
So you can use the following code to determine whether the file exists :
try: f =open() f.close()except FileNotFoundError: print ("File is not found.")except PermissionError: print ("You don't have permission to access this file.")
In fact, there is no need to deal with every exception so carefully , The above two exceptions are IOError Subclasses of . So you can simplify the program :
try: f =open() f.close()except IOError: print ("File is not accessible.")
Use try Sentence to judge , Handling all exceptions is very simple and elegant . And compared with others, there is no need to introduce other external modules .
3. Use pathlib modularpathlib Modules in Python3 In the version, there are built-in modules , But in Python2 Third party modules need to be installed separately .
Use pathlib You need to use the file path to create path object . 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()
This is about Python In this article, you can use three methods to determine whether a file exists , More about Python To judge the content of the file, please search the previous articles of the software development network or continue to browse the relevant articles below. I hope you can support the software development network in the future !