How do I check whether a file exists in Python?
Short answer
Use Path.exists from pathlib, or os.path.exists. But for the common case of opening a file, it is often better to just try and handle the error, to avoid a race condition.
The short version
Use Path("file.txt").exists() from the pathlib module, or the older os.path.exists("file.txt"). Both return True or False. For the frequent case where you check only in order to open the file, it is usually better to simply try to open it and handle the error, because the file could vanish between the check and the open.
The pathlib way
pathlib is the modern, readable option and is worth preferring for new code.
from pathlib import Path
p = Path("orders.csv")
if p.exists():
print("found it")
You can be more specific about what you are checking:
p.is_file() # exists and is a regular file, not a directory
p.is_dir() # exists and is a directory
The os way
If you are already using the os module, this does the same job.
import os
os.path.exists("orders.csv")
The race condition to understand
Checking then acting has a subtle flaw. Between exists() returning True and your open() running, another process could delete or move the file. The check does not guarantee the open will work, so the check can give false confidence.
# looks safe, is not fully safe
if Path("orders.csv").exists():
data = open("orders.csv").read() # could still fail
The preferred pattern for opening
For opening a file, the Pythonic approach is "ask forgiveness, not permission": just try, and handle the failure. This has no gap for the file to disappear in.
try:
with open("orders.csv") as f:
data = f.read()
except FileNotFoundError:
data = "" # or handle it however suits
When an explicit check is right
The check is genuinely useful when the existence itself is the question, not a prelude to opening. For example, deciding whether to create a file, skip a step, or warn the user that an expected input is missing. In those cases exists() is exactly right. When you are about to open the file anyway, prefer the try form.