import os
def check_file_exists(filename):
return os.path.isfile(filename)
print(check_file_exists("example.txt"))
If you've ever found yourself debugging a script at 2am because it just can't seem to find that one file — you know, the one that's definitely there — then you'll appreciate the importance of checking if a file exists before trying to open it. It's a simple check, but one that can save you hours of frustration. In this case, we're going to explore how to do a python check if file exists.
Using os.path.isfile()
This is probably the most straightforward way to check if a file exists in Python. The os.path.isfile() function returns True if the given path is an existing regular file, and False otherwise.
import os
filename = "example.txt"
if os.path.isfile(filename):
print(f"{filename} exists")
else:
print(f"{filename} does not exist")
I honestly prefer using this method because it's clear and concise. You can't really go wrong with it. But, there are other ways to achieve the same result.
Using os.path.exists()
This method is similar to the previous one, but it's not limited to files. It will also return True for directories and other types of paths. So, if you need to check if a file exists and you're sure that the path is a file, this might not be the best option.
import os
filename = "example.txt"
if os.path.exists(filename):
print(f"{filename} exists")
else:
print(f"{filename} does not exist")
And what about situations where you need to check multiple files? You could use a loop, but there's a more Pythonic way to do it.

Using pathlib
The
import pathlib
filenames = ["example1.txt", "example2.txt", "example3.txt"]
for filename in filenames:
path = pathlib.Path(filename)
if path.is_file():
print(f"{filename} exists")
else:
print(f"{filename} does not exist")
I have to admit, I was skeptical about using
A word on TypeScript
If you're working with TypeScript, you might be wondering how to achieve similar results. Well, it's actually quite similar.
import * as fs from 'fs';
const filename = 'example.txt';
if (fs.existsSync(filename)) {
console.log(`${filename} exists`);
} else {
console.log(`${filename} does not exist`);
}
As you can see, the syntax is almost identical. The main difference is that we're importing the fs module instead of using the built-in
Related Articles
Javascript Startswith — A Developer's Guide
A practical guide to javascript startswith with real code examples and tips from the trenches.
Javascript Check If Key Exists — A Developer's Guide
A practical guide to javascript check if key exists with real code examples and tips from the trenches.
Typescript Vs Javascript Differences — A Developer's Guide
A practical guide to typescript vs javascript differences with real code examples and tips from the trenches.