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

How to determine if a file exists in Python

anonymity
anonymityOriginal
2019-05-24 14:34:3220722browse

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)

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():
    # 指定的文件存在

Detect whether it is a directory:

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

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

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

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

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

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!

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