EN
Python - check if file exists
0
points
In this article, we would like to show you how to check if a file exists in Python.
Quick solution:
import os.path
file = os.path.exists("C:\\example_path\example.txt")
print(file) # True / False
1. Using os.path.exists()
method
In this example, we check if the file exists using exists()
method from os.path
module.
import os.path
file = os.path.exists("example.txt")
print(file) # True / False
if the file isn't directly in our project we need to specify the path:
import os.path
file = os.path.exists("C:\\example_directory\example.txt")
print(file) # True / False
2. Using os.path.isfile()
method
In this example, we check if the file exists using isfile()
method from os.path
module.
import os.path
file = os.path.isfile("example.txt")
print(file) # True / False
if the file isn't directly in our project we need to specify the path:
import os.path
file = os.path.isfile("C:\\example_directory\example.txt")
print(file) # True / False