Check if file or directory exists
Use “path.exists” method of os library to check if file or directory exists for a path
Code to Check if file or directory exists
# Imports
from os.path import exists, join
from os import getcwd
# Let's get current path
path = getcwd()
# How to check if a given directory or file exists
print(exists(path))
True
# True because above directory exists
# Now let's check for a file which doesn't exist
path = join(path, 'notpresent.abcd')
print(exists(path))
False
That's how we Check if a File or Directory exists
Related Resources:
- Make directory safely in Python Make a directory safely without raising error Use “exist_ok” parameter of makedirs method of os library to make a directory...
- Check if string contains substring python | ‘in’ keyword Check if string contains substring Use the ‘in’ keyword to check if string contains substring in python. # Let's creat...
- Create a list of files in a folder python Create a list of files in a folder python Create a list of files in a folder python | List all...
- Empty List | Learn to check if a list is empty Check if a list is empty The most pythonic and the simplest way is to use the fact “boolean value...
- Concatenate Numpy arrays | Join Numpy arrays Concatenate Numpy arrays Learn how to concatenate numpy arrays in various ways. “concatenate” method to join Numpy arrays “hstack” to...
- Key in a dictionary Python Check if a key exists in a dictionary Existence of a key can be checked by .get() method of a...
- Difference between append and extend in python Difference between append and extend Append adds an object to the end of a list whereas extend merges elements to...
- Learn Python easily with Detailed tutorials Python Learn python easily and efficiently with mini tutorials one snippet at a time. Python is widely used language for...
- Merge two dictionaries in Python Merge two dictionaries in Python Use “**- unpacking operator” to merge two dictionaries # Let's create two dictionaries a =...
- Convert unix timestamp string to readable date in Python Unix Timestamp Conversion Converting unix timestamp string to readable date in python Converting unix timestamp string to readable date in...