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 .
os Module os.path.exists() Method is used to verify the existence of a file .
import os
os.path.exists(test_file.txt)
#True
os.path.exists(no_exist_file.txt)
#False
import os
os.path.exists(test_dir)
#True
os.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 :
import os
os.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 :
This method returns by judging whether the file path exists and the permissions of various access modes True perhaps False.
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")
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 :
'''
No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :660193417###
Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book !
'''
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 .
pathlib 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 .
path = pathlib.Path("path/file")
path.exist()
path = pathlib.Path("path/file")
path.is_file()