Lesson 10 of 19
File Handling
Read and write text files safely.
Introduction
The with statement opens a file and closes it automatically. Use read_text or open with a mode such as r, w or a.
Writing replaces existing content in w mode, so use a for adding new content.
Key insight
Read and write text files safely.
Example
with open("notes.txt", "w") as file:
file.write("Keep practicing!")
with open("notes.txt") as file:
print(file.read())This example shows the core file handling idea in a small, runnable program.
Real-world example
Scripts use files for exports, logs and small configuration values.
Test yourself
2-question check
1
What is the main idea in File Handling?
2
Where can file handling be useful?
Ready to check your understanding?
Answer every question, then submit your quiz.
Try it yourself
Python compiler
Runs in your browser. Nothing is sent to a server.
Output appears here
First run downloads the Python runtime, so it may take a moment.
Practice challenge
Append one new line to a text file.