Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if directory exists in Python

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 
like image 682
David542 Avatar asked Jan 19 '12 21:01

David542


People also ask

How do you check if it is a directory?

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.

How do I search for a current directory in Python?

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.

How do you check if a file already exists in Python?

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 .

How do you check if a file is present in a folder using Python?

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.


2 Answers

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 
like image 59
phihag Avatar answered Sep 25 '22 08:09

phihag


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.

like image 35
joelostblom Avatar answered Sep 25 '22 08:09

joelostblom