🟢 Beginner · Lesson 19
File Handling in Python
What is File Handling?
File handling lets a program save data to a file and read it back later — so data is not lost when the program ends. This is how real apps store notes, records and reports.
File Modes
| Mode | Meaning |
|---|---|
| "r" | Read (file must exist) |
| "w" | Write (creates new / erases old) |
| "a" | Append (add to the end) |
| "r+" | Read and write |
Open, Read, Close
The basic flow: open() the file, do your work, then close() it. Better still, use with which closes automatically.
Program 1: Write to a File
Python – write.py
f = open("notes.txt", "w")
f.write("Hello from Python\n")
f.write("This is line 2\n")
f.close()
print("File written successfully")File written successfully
"w"createsnotes.txt(or erases it if it exists).\nmoves to a new line;.close()saves the file.
Program 2: Read a File
Python – read.py
f = open("notes.txt", "r")
content = f.read()
f.close()
print(content)Hello from Python
This is line 2
.read() returns the whole file as one string.
Program 3: Append Data
Python – append.py
f = open("notes.txt", "a")
f.write("This line was added later\n")
f.close()
print("Line appended")Line appended
"a" keeps the old content and adds the new line at the end (unlike "w" which erases).
Program 4: Read Line by Line with `with`
Python – withread.py
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
# file closes automatically hereHello from Python
This is line 2
This line was added later
withcloses the file automatically — even if an error happens.- Looping over
freads one line at a time (memory-friendly). .strip()removes the extra newline.
Common Mistakes
- Using
"w"when you meant"a"— it erases the file! - Forgetting to close the file (use
withto be safe). - Opening a non-existent file in
"r"mode → FileNotFoundError.
Practice Tasks
- Write 5 student names to a file, one per line.
- Read the file and count how many lines it has.
- Append today's date to a log file each time the program runs.
- Read a file and print it in UPPERCASE.
Summary
- File handling saves and reads data permanently.
- Modes:
"r"read,"w"write/erase,"a"append. - Use
with open(...) as f:— it closes the file automatically.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.