Multi-Exception File Reader
Write a program that saves some text to a file called existing.txt, then attempts to open and read a given filename — handling FileNotFoundError with one message and any other exception with a generic message, using a finally block that always prints a completion message.
What the problem means: exercise a full try/except/except/finally structure where the outcome depends on whether the filename you're asked to read actually exists.
Approach: write the given content into existing.txt first. Then try to open and read the given filename — if it's existing.txt, the read succeeds; for any other name, it raises FileNotFoundError. Either way, the finally block always runs last.
Input: Two lines: the text content to save into existing.txt, then the filename to attempt reading.
Output: The file's content (if the given filename was found and read), or File not found. — followed on the next line by Read attempt complete either way.
Hello missing.txt
File not found. Read attempt complete
- The filename to read is either exactly "existing.txt" or some other name that doesn't exist.
Hint 1
Write the content to existing.txt before attempting to read the requested filename.
Hint 2
except FileNotFoundError: handles a missing file specifically; a later except Exception: is a safety net for anything else.
Hint 3
The finally: block runs no matter which branch (or neither) executed.
After saving the given content into existing.txt, the program tries to open and read whatever filename was requested. If that name is existing.txt, the read succeeds and prints the content; for any other name, Python raises FileNotFoundError, caught by its own except block printing "File not found.". Either way, the finally: block runs last and unconditionally prints "Read attempt complete".