Python File Handling Cheat Sheet
1. File Modes
Mode Read Write Append Truncate Cursor start
r ✅ ❌ ❌ ❌ Start
w ❌ ✅ ❌ ✅ Start
a ❌ ✅ ✅ ❌ End
r+ ✅ ✅ ❌ ❌ Start
w+ ✅ ✅ ❌ ✅ Start
a+ ✅ ✅ ✅ ❌ End
Tip: Use [Link](0) to read from start after writing.
2. Reading Methods
[Link]() - read entire file
with open("[Link]", "r") as f:
print([Link]())
[Link]() - read one line
with open("[Link]", "r") as f:
print([Link]())
print([Link]())
[Link]() - read all lines into list
with open("[Link]", "r") as f:
lines = [Link]()
print(lines)
Iterate line by line
1
with open("[Link]", "r") as f:
for line in f:
print([Link]())
3. Writing Methods
[Link](string) - write single string
with open("[Link]", "w") as f:
[Link]("Hello Python\n")
[Link](list_of_strings) - write multiple strings
lines = ["Line1\n", "Line2\n", "Line3\n"]
with open("[Link]", "w") as f:
[Link](lines)
Note: writelines() does not add \n automatically.
4. Cursor Management
with open("[Link]", "a+") as f:
[Link]("New Line\n")
[Link](0) # Move cursor to start
print([Link]())
5. Examples by Mode
Read Mode r
with open("[Link]", "r") as f:
print([Link]())
Write Mode w
with open("[Link]", "w") as f:
[Link]("This will overwrite content\n")
2
Append Mode a
with open("[Link]", "a") as f:
[Link]("Appended line\n")
Read + Write r+
with open("[Link]", "r+") as f:
[Link]("Overwrite from start\n")
[Link](0)
print([Link]())
Write + Read w+
with open("[Link]", "w+") as f:
[Link]("New content\n")
[Link](0)
print([Link]())
Append + Read a+
with open("[Link]", "a+") as f:
[Link]("Appended line\n")
[Link](0)
print([Link]())
6. Quick Tips
1. Always use with open(...) → automatically closes file.
2. Use seek(0) to read after writing in r+ , w+ , or a+ .
3. Include \n when using writelines() to keep lines separate.
4. Iterate line by line for large files.
5. Append modes never delete existing content.
💡 Memory trick: Modes are like 3 letters: r =read, w =write (truncate), a =append, + =both read &
write.