How do I check if Python directory exists?
I’ve been working with file systems for a while, and one quick way to python check if directory exists is by using os.path.exists()
. It checks if a file or directory exists at a specified path:
import os
directory = "/path/to/directory"
if os.path.exists(directory):
print("Directory exists")
else:
print("Directory does not exist")
This works for both files and directories, so it’s pretty versatile!
That’s a great start, Rima! Just to refine it a bit further, if you specifically want to python check if directory exists and not just any file, os.path.isdir()
is more precise. Here’s how you could do it:
import os
directory = "/path/to/directory"
if os.path.isdir(directory):
print("Directory exists")
else:
print("Directory does not exist")
This way, you’re strictly checking for directories only.
Both methods are fantastic! But if you’re leaning toward a more modern, object-oriented approach, the pathlib
module is worth exploring. When I need to python check if directory exists, I often use Path.is_dir()
from pathlib
—it’s concise and Pythonic:
from pathlib import Path
directory = Path("/path/to/directory")
if directory.is_dir():
print("Directory exists")
else:
print("Directory does not exist")
pathlib
works seamlessly with other filesystem operations, so it’s great for more complex scripts.