深度阅读

How to Check if a File Exists in Python with isFile() and exists()

作者
作者
2023年08月22日
更新时间
12.58 分钟
阅读时间
0
阅读量

To check if a file exists in Python, you have multiple options. Here are three common methods:

  1. Using the os.path.isfile function:
import os.path

if os.path.isfile('/path/to/file'):
   # file exists
else:
   # file does not exist
  1. Using the pathlib.Path.is_file method:
from pathlib import Path

if Path('/path/to/file').is_file():
   # file exists
else:
   # file does not exist
  1. Using the os.path.exists function:
import os.path

if os.path.exists('/path/to/file'):
   # file exists
else:
   # file does not exist

Note that if you are using Python 3 with pathlib, you may find the second method easier to read and work with. Additionally, os.path.isfile and os.path.exists can also be used to check if a path exists and is a directory instead of a file via os.path.isdir.

Here’s an example using os.path.isfile to check if a file exists:

import os.path

file_path = '/path/to/file'
if os.path.isfile(file_path):
    print(f'The file {file_path} exists.')
else:
    print(f'The file {file_path} does not exist.')

This will output either “The file /path/to/file exists.” or “The file /path/to/file does not exist.”, depending on whether or not the file exists at the specified path.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。