How do I check if directory exists in Python?
You can use the os module to check if a directory exists.
You can use the os module to check if a directory exists. Here is an example of how you can do it:
Check if directory exists in Python using the os.path.isdir function
import os
# Check if directory exists
if os.path.isdir("./my_folder"):
# Do something
pass
else:
# Do something else
pass
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
Alternatively, you can use the os.path.exists() function to check if a path exists. Note that this function returns True for both files and directories, so it is less specific than isdir().
Here is an example of how you can use os.path.exists() to check if a directory exists:
Check if directory exists in Python using the os.path.exists function
import os
# Check if directory exists
if os.path.exists("./my_folder"):
# Do something
pass
else:
# Do something else
passWhen to use which?
- Use
os.path.isdir()when you specifically need to verify that the path is a directory. - Use
os.path.exists()when you only need to know if any file or directory exists at that path.
Modern alternative: pathlib
In modern Python (3.4+), the pathlib module provides an object-oriented approach:
from pathlib import Path
if Path("./my_folder").is_dir():
# Directory exists
pass