This post will show you how to check if a file exists or not in Python. Often, we want to check if a file exists or not before trying to do any file operations. For example, before reading contents from a file or before writing anything to a file, we can check if it exists or not.
This post will show you two different ways to check if a file exists. Let’s take a look at these one by one.
os.path.exists method is used to check if a path exists or not in Python. It takes one path as the parameter and returns one boolean value. It returns True if the path exists, else it returns False.
We can also use os.path.isfile(path) method. This method returns True if the given path is for an existing regular file.
from os.path import exists file_path = 'sample.txt' if exists(file_path): print("File exists") else: print("File doesn't exists")
Similarly, we can use isfile as like below:
from os.path import isfile file_path = 'sample.txt' if isfile(file_path): print("Given path is a file") else: print("Given path is not a file")
Starting from Python 3.4, we can also use pathlib module. This module can be used to create a Path object by providing the path of the file. Path class provides one method called is_file() which can be used to check if the given path is a file or not.
Below program shows how to do that:
from pathlib import Path file_path = 'sample.txt' f = Path(file_path) if f.is_file(): print("Given path is a file") else: print("Given path is not a file")
is_file() method returns one boolean value and based on it, we can say the path is a file or not.
- How to convert float to integer in Python
- How to create a new text file in python
- How to truncate datetime object and get the date in Python
- How to decrement a for loop in Python
- Split the root, extension of a path in Python using os.path.splitext
- Python program to replace all negative numbers with zero in a list