File Handling (Read/Write)
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — What Are Files?
In programming, files let you save data permanently. Without files, everything disappears when the program stops. Think of it like saving your progress in a game — without a save file, you'd lose everything!
Let's see how to create a file and write to it. We use the `open()` function to work with files. To write, we open the file in "w" mode.
file = open("team.txt", "w")
file.write("Aquachu")
file.close()
print("File saved!")Write Mode
"w" means write mode. It creates the file if it doesn't exist, and overwrites it if it does.
Exercise 2 — Reading a File
To read a file, we use `open()` with "r" mode (read).
file = open("team.txt", "w")
file.write("Aquachu\nPyrochu\nFlorachu")
file.close()
file = open("team.txt", "r")
content = file.read()
file.close()
print(content)In this example, we first create the file and put 3 Codémon names in it. Then we open it in read mode, read the content, and print it.
All modes of open()
- `"r"` (read): read from file - `"w"` (write): write to file (overwrites existing content) - `"a"` (append): add to end of file - `"x"` (eXclusive creation): create file, but fail if it already exists
Exercise 3 — File Modes
What does the "a" mode do when opening a file?
Hint : `"r"` is for read, `"w"` is for write (overwrite), and `"a"` is for ..?
Exercise 4 — Write to a File
Complete the code to write a Codémon name to a file.
Hint : To write, you need write mode and the write method.
Exercise 5 — The with Statement
You probably saw that we have to write file.close() every time, which is annoying. Python has a better way: the `with` statement. It automatically closes the file for you!
with open("team.txt", "w") as file:
file.write("Aquachu\nPyrochu")
with open("team.txt", "r") as file:
print(file.read())Best Practice
with is the recommended way to work with files. It's cleaner and safer — the file is always closed, even if an error occurs.
Exercise 6 — Using with
Complete the code to read a file using with.
Hint : To read, you need the right mode and the right method.
Exercise 7 — File Operations
Match each file mode or method with its description.
Exercise 8 — Codémon Save System
Create a save system for your Codémon team!
1. Write a file "save.txt" with 1 Codémon name
2. Read the file and print the content
3. Append a 2nd Codémon using "a" mode (on a new line)
4. Read and print the updated file
Use the with statement!
# 1. Write 1 Codémon to save.txt
# 2. Read and print
# 3. Append a 2nd Codémon
# 4. Read and print the updated save