Python Practice › Exception Handling Programs › Program 13
Handle a missing file
Write a Python program that opens a file and handles the case where it does not exist.
Output
exists.txt -> hello missing.txt -> not found
Approach
- Catch
FileNotFoundError.
Solution
for name in ["exists.txt", "missing.txt"]: if name == "exists.txt": with open(name, "w") as f: f.write("hello") try: with open(name) as f: print(name, "->", f.read()) except FileNotFoundError: print(name, "-> not found")Output
exists.txt -> hello missing.txt -> not found
Learn the concept
New to this topic? Read the lesson, then come back.