Home > Backend Development > Python Tutorial > How to determine if a file exists in Python

How to determine if a file exists in Python

anonymity
Release: 2020-09-18 09:35:01
Original
20840 people have browsed it

How Python determines whether a file exists: You can use the os.path.exists() method in the os module to determine, such as [if my_file.exists()]. Before starting the judgment, you need to execute the [import os.path] statement to import the os module.

How to determine if a file exists in Python

When Python operates files, we generally need to first determine whether the specified file or directory exists, otherwise exceptions may easily occur.

For example, we can use the os.path.exists() method of os module to detect whether the file exists:

import os.path
os.path.isfile(fname)
Copy after login

If you want to determine whether it is a file or a directory, Starting from Python 3.4, you can use the object-oriented method provided by the pathlib module (Python 2.7 is the pathlib2 module):

from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
    # 指定的文件存在
Copy after login

Detect whether it is a directory:

if my_file.is_dir():
    # 指定的目录存在
Copy after login

If you want to detect whether the path is a file or The directory can use the exists() method:

if my_file.exists():
    # 指定的文件或目录存在
Copy after login

In the try statement block, you can use the resolve() method to determine:

try:
    my_abs_path = my_file.resolve()except FileNotFoundError:
    # 不存在else:
    # 存在
Copy after login

The above is the detailed content of How to determine if a file exists in Python. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template