Skip to content
AgileLogics
4 min read

File Handling

Prerequisites: Basic error handling

open() reads from or writes to a file. The with statement automatically closes the file afterward, even if an error occurs inside the block.

with open("notes.txt", "w") as file:
    file.write("Hello, file!")

with open("notes.txt", "r") as file:
    content = file.read()
    print(content)

Expected output

Hello, file!

"w" opens for writing (overwrites existing content), "r" for reading, and "a" appends to the end without erasing what's already there.

Common mistakes

  • Forgetting with, and forgetting to call .close() manually — an unclosed file can lose unsaved data or lock the file for other programs.