Thursday, January 23, 2025
HomeQ&APython - How to Check if a file or directory exists

Python – How to Check if a file or directory exists

In Python, you can use the os module or the pathlib module to check if a file or directory exists. Below are examples of both methods:

Using os module:

import os

# Check if a file exists
if os.path.isfile('path/to/file'):
    print("File exists")
else:
    print("File does not exist")

# Check if a directory exists
if os.path.isdir('path/to/directory'):
    print("Directory exists")
else:
    print("Directory does not exist")

Using pathlib module (recommended for modern Python code):

from pathlib import Path

# Check if a file exists
file_path = Path('path/to/file')
if file_path.is_file():
    print("File exists")
else:
    print("File does not exist")

# Check if a directory exists
directory_path = Path('path/to/directory')
if directory_path.is_dir():
    print("Directory exists")
else:
    print("Directory does not exist")

The pathlib module is generally considered more flexible and easier to use for path-related tasks, so it’s often preferred in newer code.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x