Home  >  Article  >  Backend Development  >  How to check if a folder exists in python and create it if it doesn't exist

How to check if a folder exists in python and create it if it doesn't exist

silencement
silencementOriginal
2019-05-25 15:02:2511532browse

How to check if a folder exists in python and create it if it doesn't exist

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

How to check if a folder exists in python and create it if it doesnt exist

Judge whether the file exists

How to check if a folder exists in python and create it if it doesnt exist

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:

How to check if a folder exists in python and create it if it doesnt exist

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn