Path("name").exists() from the pathlib module returns True if something with that name exists. Use is_file() or is_dir() when you need to know whether it is a file or a folder.
The program
python
from pathlib import Path # create one file and one folder to test with Path("report.txt").write_text("Quarterly report", encoding="utf-8") Path("photos").mkdir() for name in ["report.txt", "photos", "missing.txt"]: path = Path(name) if path.is_file(): print(f"{name}: file, {path.stat().st_size} bytes") elif path.is_dir(): print(f"{name}: folder") else: print(f"{name}: not found")
output
report.txt: file, 16 bytes photos: folder missing.txt: not found
How it works
Path("report.txt")does not open or create anything. It is an object that stands for a path, with methods that ask the operating system about it.exists()isTruefor files and folders.is_file()isTrueonly for a file, andis_dir()only for a folder. All three areFalsewhen nothing is there.stat().st_sizeis the size in bytes. "Quarterly report" is 16 characters, and each one takes 1 byte.
The os.path way
Older code uses the os.path module. It does the same checks with functions:
python
import os with open("report.txt", "w", encoding="utf-8") as f: f.write("Quarterly report") print(os.path.exists("report.txt")) print(os.path.isfile("report.txt")) print(os.path.getsize("report.txt")) print(os.path.exists("missing.txt"))
output
True True 16 False
If you check only so that you can open the file next, use try / except FileNotFoundError instead. Another program could delete the file between your check and your open(), and try handles that case too.