Python Learning Series · @onlysamarrr · Day 26 / 30
Day 26 teaches file handling. open() opens a file: 'w' writes and erases old content, 'a' appends, 'r' reads. The with statement closes the file automatically, so you never forget close().
Phase: Intermediate · Reels: 126/450 – 130/450
Day 26 teaches file handling. open() opens a file: 'w' writes and erases old content, 'a' appends, 'r' reads. The with statement closes the file automatically, so you never forget close().
with open("notes_demo.txt", "w", encoding="utf-8") as f:
f.write("Line 1\nLine 2\n")
with open("notes_demo.txt", "a", encoding="utf-8") as f:
f.write("Line 3\n")
with open("notes_demo.txt", encoding="utf-8") as f:
lines = f.readlines()
print(len(lines))
print(lines)
3 ['Line 1\n', 'Line 2\n', 'Line 3\n']
Logs, notes apps and saved settings all write to files.
Select (tick) an option, then tap Check answer to see instantly whether your answer is right or wrong, with an explanation. You can change your answer and check again.
Q1. What does open("f.txt", "w") do to existing content?
Q2. Which mode appends without erasing?
Q3. Why use with when opening a file?
| 126/450 | Concept | open, read, write |
| 127/450 | Live demo | Notes app file mein save |
| 128/450 | Common mistake | Mode w file mita deta |
| 129/450 | Quiz | Quiz: lines count karo |
| 130/450 | Interview / real life | Real life: logs likhna |