Languages
[Edit]
EN

Python - check if file exists

0 points
Created by:
Dale-K1
327

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

Python - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join