Python File Handling
1. Opening a File (open() and with open())
file = open("[Link]", "r") # Open file in read mode
[Link]() # Always close the file after use
with open("[Link]", "r") as file:
pass # 'with' automatically closes the file after use
Modes:
• "r" → Read (default, file must exist)
• "w" → Write (creates or overwrites file)
• "a" → Append (adds to file, doesn’t overwrite)
• "r+" → Read & Write (file must exist)
• "w+" → Read & Write (creates or overwrites)
• "a+" → Read & Append (creates if missing)
• "rb", "wb", "ab" → Binary mode
2. Reading a File
file = open("[Link]", "r")
print([Link]()) # Reads the entire file
[Link]()
file = open("[Link]", "r")
print([Link]()) # Reads one line
[Link]()
file = open("[Link]", "r")
print([Link]()) # Reads all lines as a list
[Link]()
3. Writing to a File
file = open("[Link]", "w")
[Link]("Hello, Python!") # Overwrites the file
[Link]()
file = open("[Link]", "w")
[Link](["Line 1\n", "Line 2\n"]) # Writes multiple lines
[Link]()
4. Appending to a File
file = open("[Link]", "a")
[Link]("\nNew Line Added") # Adds without deleting previous content
[Link]()
5. Seek & Tell (Moving Cursor in File)
file = open("[Link]", "r")
print([Link]()) # Get current cursor position
[Link](5) # Move cursor to position 5
print([Link]()) # Read from new position
[Link]()
Summary
• Read: read(), readline(), readlines()
• Write: write(), writelines()
• Modes: "r", "w", "a", "r+", "w+", "a+"
• Seek & Tell: seek(position), tell()
• Use with for auto file closing (recommended but not required).