In the development of Python, we often encounter the need to determine the existence of documents, today and we share this part of the content, I hope to learn python to help you.
It is also a good programming practice to check the existence of a file before manipulating it. Typically, there are three common ways to determine whether a folder or file exists, namely the OS module, the try statement, and the Pathlib module.
OS Module
The os.path.exists (path) in the OS module detects whether a file or folder exists and path is the name/absolute path of the file/folder. Returns the result as True/false
Print os.path.exists ("/untitled/chapter3.py")
Print os.path.exists ("chapter3.py")
This usage can detect both the file and the folder, which also poses a problem, if I want to find a file named HelloWorld, using exists may hit the HelloWorld folder with the same name. This can be distinguished by using os.path.isdir () and Os.path.isfile (). If you want to further determine whether you can manipulate the file, you can use Os.access (path, model), model for the operating mode, as follows
if __name__ = = ' __main__ ':
if os.access ("/untitled/chapter3.py", OS. F_OK):
Print "File path is exist."
if os.access ("/untitled/chapter3.py", OS. R_OK):
Print "File is accessible to read"
if os.access ("/untitled/chapter3.py", OS. W_OK):
Print "File is accessible to write"
if os.access ("/untitled/chapter3.py", OS. X_OK):
Print "File is accessible to execute"
Try Statement
The simplest way to manipulate a file is to use the open () method directly, but the file does not exist, or the open method causes an error when a permission problem occurs, so it is used with the try statement to catch an exception. Try...open syntax is simple, elegant, readable, and does not require any modules to be introduced
if __name__ = = ' __main__ ':
Try:
f = open("/untitled/chapter3.py")
F. Close ()
Except IOError:
Print "File is not accessible."
Pathlib Module
Pathlib belongs to third-party modules in Python2 and needs to be installed separately. But Python3 Pathlib is already built into the module.
Pathlib is simple to use and similar to open. Use Pathlib to create objects first, using exists (), is_file (), etc.
if __name__ = = ' __main__ ':
Path = Pathlib. Path ("chapter3.py")
print path.exists ()
print path.is_file ()
Source: Push Cool
Python determines whether a file exists