PythonMastery

How do I check if a file exists in Python?

Path('notes.txt').exists() answers it. About to open the file anyway? Skip the check and catch FileNotFoundError: the file can vanish in between.

pathlib.Path has the answer as a method.

python
from pathlib import Path

Path("notes.txt").touch()   # create an empty file, so there's one to find

print(Path("notes.txt").exists())
print(Path("missing.txt").exists())
output
True
False

exists() is also True for a folder. If it has to be a file, ask that instead:

python
from pathlib import Path

Path("reports").mkdir(exist_ok=True)

print(Path("reports").exists())
print(Path("reports").is_file())
print(Path("reports").is_dir())
output
True
False
True

If you're going to open it anyway, don't check first

This is the pattern most people write:

python
from pathlib import Path

path = Path("settings.json")
if path.exists():
    text = path.read_text(encoding="utf-8")
else:
    text = "{}"
print(text)
output
{}

It has a gap. Between exists() and read_text(), another program can delete or move the file, and your "safe" code crashes anyway. Ask for forgiveness instead: open it, and handle the one error that means "not there".

python
from pathlib import Path

try:
    text = Path("settings.json").read_text(encoding="utf-8")
except FileNotFoundError:
    text = "{}"
print(text)
output
{}

Same result, one less step, and no window for things to change. Keep exists() for when the answer itself is what you need, such as "skip this download, we already have it".

Still getting FileNotFoundError on a file you can see?

The path is relative to where Python was started, not to where your script lives. Print Path.cwd() to see which folder that is; the error page has the fix.

Go deeper: File I/O, Pathlib, and Large Files, FileNotFoundError: [Errno 2] No such file or directory

More short answers

all questions