178. Python Program to Read a File Safely with try and except
Mediumwith
Overview
A user can type the name of a file that doesn't exist. Catch FileNotFoundError instead of crashing.
Problem Statement
First, use a with block to write these three lines into a file called notes.txt:
Buy milk
Call Sunny
Feed Rocky
Then read a file name. Open that file with with, inside try, and print each of its lines with - in front (strip the newline). If the file doesn't exist, catch the FileNotFoundError and print File not found: followed by the name.
Your program runs in the browser, so the file lives only in this tab's memory. Create it with "w" before you read it.
Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Input
One line: a file name. Example:
notes.txt
Output
The output for that example:
- Buy milk\
- Call Sunny\
- Feed Rocky
For the input notes.text, the output is:
File not found: notes.text
The tests try 4 different names. Names must match exactly: Notes.txt is not notes.txt.