1. Use the os module
The os.path.exists() method in the os module is used to check whether the folder exist.
Judge whether the folder exists
Judge whether the file exists
You can see that using os The .path.exists() method determines whether the file and folder are the same.
2. Use the try statement
You can directly use the open() method in the program to check whether the file exists and is readable and writable.
Syntax:
open()
If the file you open does not exist, the program will throw an error, use the try statement to catch this error.
The program cannot access the file. There may be many reasons:
If the file you open does not exist, a FileNotFoundError exception will be thrown;
The file exists, but there is no permission. Access will throw a PersmissionError exception.
So you can use the following code to determine whether the file exists:
The above is the detailed content of How to check if a folder exists in python and create it if it doesn't exist. For more information, please follow other related articles on the PHP Chinese website!