Python File Handling
1. Opening a File (open() and with open())
file = open("example.txt", "r") # Open file in read mode
file.close() # Always close the file after use
with open("example.txt", "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("example.txt", "r")
print(file.read()) # Reads the entire file
file.close()
file = open("example.txt", "r")
print(file.readline()) # Reads one line
file.close()
file = open("example.txt", "r")
print(file.readlines()) # Reads all lines as a list
file.close()
3. Writing to a File
file = open("example.txt", "w")
file.write("Hello, Python!") # Overwrites the file
file.close()
file = open("example.txt", "w")
file.writelines(["Line 1\n", "Line 2\n"]) # Writes multiple lines
file.close()
4. Appending to a File
file = open("example.txt", "a")
file.write("\nNew Line Added") # Adds without deleting previous content
file.close()
5. Seek & Tell (Moving Cursor in File)
file = open("example.txt", "r")
print(file.tell()) # Get current cursor position
file.seek(5) # Move cursor to position 5
print(file.read()) # Read from new position
file.close()
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).