深度阅读

How to check if a file or directory exists in Python using os.path.exists()?

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

To check if a file or directory exists in Python, you can use the os.path.exists() method from the os library. This method takes the path to the file or directory as its input and returns True if the file or directory exists, and False otherwise. Here is an example:

import os

path = "/path/to/file_or_directory"
if os.path.exists(path):
    print("File or directory exists!")
else:
    print("File or directory does not exist!")

This example checks if the file or directory located at /path/to/file_or_directory exists using os.path.exists() and prints an appropriate message to the console.

Note that os.path.exists() returns True for both files and directories, so if you need to check for the existence of a directory specifically, you can use os.path.isdir().

Using os.path.exists() is useful when you need to check if a file or directory exists before performing operations on it, like opening, reading, writing, or deleting the file or directory.

相关标签

博客作者

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