Python File Handling Practice Questions for Beginners
Chapter 19 Recap and Practice
Your programs can now keep their data in files. Here is the chapter in one table:
| You write | It does |
|---|---|
f = open("notes.txt", "w") | opens a file and gives back a file object |
f.close() | closes the file; a closed file can't be used |
"r" | read only; the default mode; a missing file gives FileNotFoundError |
"w" | empties the file (or makes it), then writes |
"a" | adds to the end (or makes the file), keeps the old text |
f.write("Sunny\n") | writes one string; add the "\n" yourself; numbers need str() |
f.read() | the whole file as one string, newlines and all |
f.readline() | the next line, with its "\n" |
f.readlines() | a list of all the lines |
for line in f: | loops over the lines; line.strip() removes the newline |
with open("notes.txt") as f: | closes the file for you, even after an error |
except FileNotFoundError: | handles a file that isn't there |
line.strip().split(",") | splits a saved name,score line back into its parts |
And remember: in LivePython, files live in the browser tab's memory and disappear when you reload. That's why every program here writes its file first, then reads it.
Practice questions
Use input() with no prompt text. Each program creates the files it reads, so it gives the same output every time it runs. The tests try several inputs, so test your program with a few of your own too.
Open a file and file modes
- 170.Python Program to Save a Name in a File and Read It BackEasySolve
- 171.Python Program to Copy a Text FileMediumSolve
Write and append
- 172.Python Program to Write a Shopping List to a FileEasySolve
- 173.Python Program to Append Entries to a Diary FileMediumSolve
Read a file
- 174.Python Program to Read a File Line by LineEasySolve
- 175.Python Program to Count Lines and Words in a FileMediumSolve
- 176.Python Program to Find a Word in a FileMediumSolve
with open() and FileNotFoundError
- 177.Fix the Python Program That Never Closes Its FileEasySolve
- 178.Python Program to Read a File Safely with try and exceptMediumSolve
- 179.Python Program to Save and Load a Score ListHardSolve
Files let your programs remember things after they end. Next, you'll learn object-oriented programming: how to build your own types with classes.