Tags
python
Asked 2 years ago
16 Aug 2021
Views 318
Santiago

Santiago posted

How do I check if a directory exists in Python?

How do I check if a directory exists in Python?
kord

kord
answered Feb 25 '23 00:00

You can check if a directory exists in Python using the os.path module. Here's an example:



import os

directory = '/path/to/directory'

if os.path.exists(directory):
    print("Directory exists")
else:
    print("Directory does not exist")

In this example, the os.path.exists() function is used to c heck if the directory specified by the directory variable exists . If it exists , the program prints "Directory exists", otherwise it prints "Directory does not exist".

Alternatively, you can use the os.path.isdir() function to check if a given path exists and is a directory:


import os

directory = '/path/to/directory'

if os.path.isdir(directory):
    print("Directory exists")
else:
    print("Directory does not exist")


In this example, the os.path.isdir() function is used to check if the directory variable exists and is a directory. If it is, the program prints "Directory exists", otherwise it prints "Directory does not exist".
Post Answer