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

silencement
Release: 2019-05-25 16:22:37
Original
11505 people have browsed it

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!