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
path. isdir is the easiest way to check if a directory exists, or if the path given is a directory. Again, just like isfile , os.
Python can search for file names in a specified path of the OS. This can be done using the module os with the walk() functions. This will take a specific path as input and generate a 3-tuple involving dirpath, dirnames, and filenames.
To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .
In Python, you can check whether certain files or directories exist using the isfile() and isdir() methods, respectively. However, if you use isfile() to check if a certain directory exists, the method will return False. Likewise, if you use if isdir() to check whether a certain file exists, the method returns False.
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
Python 3.4 introduced the pathlib
module into the standard library, which provides an object oriented approach to handle filesystem paths. The is_dir()
and exists()
methods of a Path
object can be used to answer the question:
In [1]: from pathlib import Path In [2]: p = Path('/usr') In [3]: p.exists() Out[3]: True In [4]: p.is_dir() Out[4]: True
Paths (and strings) can be joined together with the /
operator:
In [5]: q = p / 'bin' / 'vim' In [6]: q Out[6]: PosixPath('/usr/bin/vim') In [7]: q.exists() Out[7]: True In [8]: q.is_dir() Out[8]: False
Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With