pathlib.Path has the answer as a method.
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())
True False
exists() is also True for a folder. If it has to be a file, ask that instead:
from pathlib import Path Path("reports").mkdir(exist_ok=True) print(Path("reports").exists()) print(Path("reports").is_file()) print(Path("reports").is_dir())
True False True
If you're going to open it anyway, don't check first
This is the pattern most people write:
from pathlib import Path path = Path("settings.json") if path.exists(): text = path.read_text(encoding="utf-8") else: text = "{}" print(text)
{}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".
from pathlib import Path try: text = Path("settings.json").read_text(encoding="utf-8") except FileNotFoundError: text = "{}" print(text)
{}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.