Sometimes you may need to check if a directory exists before performing certain operations in it, such as creating a new file in the folder. You can easily do this in a couple of ways using os module. In this article, we will learn how to check if directory exists in Python.
How to Check if Directory Exists in Python
You can use os.path.isdir() function to check if a folder exists in python. Here is an example to check if /home/data folder exists.
>>> import os >>> os.path.isdir('/home/data') True
isdir() returns True if the input path exists, else it returns False. You need to provide the full path to folder in isdir() command. If you provide only relative path, then python interpreter will check the path relative to its current folder location.
If you don’t care whether the path is a file or folder, you can also use os.path.exists. Here is an example to check file /data/file.txt
>>> import os >>> os.path.exists('/home/data/file.txt') False
The above function returns True if the file or folder exists, else it returns false. Here also, you need to provide full path to file or folder. If you provide relative path, it will consider it as path relative to current folder during execution.
The difference between isdir() and exists() function is that isdir() works only with folders where exists() works with both files & folders. So you can also use exists() to check if a file exists or not.
Alternatively, you can also use pathlib module.
>>> from pathlib import Path >>> Path('/home/data').is_dir() True
You can run these commands in python shell or embed it in your Python script, as you need. If you need to check if a folder exists, you can use isdir() function but if you want to keep things flexible and check both files & folders, you can use exists() function. In this article, we have learnt how to check if directory exists in Python.
How to Get Directory of Shell Script
How to Create Multiline String in Python
How to Disable SSH Authentication for Some Users
How to Kill Process Running Longer Than Specific Time
How to Split Tar into Multiple Files in Linux