How to find if directory exists in Python
Posted By: Anonymous
In the os
module in Python, is there a way to find if a directory exists, something like:
>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
Solution
You’re looking for os.path.isdir
, or os.path.exists
if you don’t care whether it’s a file or a directory:
>>> import os
>>> os.path.isdir('new_folder')
True
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False
Alternatively, you can use pathlib
:
>>> from pathlib import Path
>>> Path('new_folder').is_dir()
True
>>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
False
Answered By: Anonymous
Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.