🧪 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? |
|---|---|---|---|
| Read | No | No (Error if missing) |
| Write | Yes | Yes |
| Append | No | Yes |
| Create | Error if exists | Yes |