Python Mastery – From Basics to Brilliance / File Handling

Reading and Writing Files

🧪 Example: Reading Line by Line

with open("data.txt", "r") as file:
    for line in file:
        print(line.strip())

Useful for large files—reads one line at a time without loading the whole file into memory.


✍️ Appending to a File

with open("log.txt", "a") as file:
    file.write("\\nAnother log entry.")

Use "a" mode to add data without erasing the old content.


🚫 Common Mistake

Forgetting to close a file:

file = open("data.txt", "r")
data = file.read()
# file.close() is needed manually

# Better:
with open("data.txt", "r") as file:
    data = file.read()  # Automatically closed

📘 Summary Table

Mode

Action

Overwrites?

Creates File?

r

Read

No

No (Error if missing)

w

Write

Yes

Yes

a

Append

No

Yes

x

Create

Error if exists

Yes