File Handling — Read, Write & Delete
Files store data on disk — logs, configs, CSV exports. Always close files or use with open(...).
Python File Handling
Files store data on disk — logs, configs, CSV exports. Always close files or use with open(...).
Modes: 'r' read, 'w' write (overwrite), 'a' append, 'x' create if missing.
Real-life example: File handling is a notebook — read pages, write new notes, tear out old ones (delete).
Python Read Files
read() loads entire file; readline() one line; readlines() list of lines.
Loop directly over the file object for memory-efficient reading of large files.
Real-life example: Reading a file line by line is reading a novel page by page instead of memorizing the whole book.
with open("notes.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())Python Write/Create Files
Mode 'w' creates or overwrites. 'a' adds to the end without erasing.
Specify encoding='utf-8' for international text.
Real-life example: Writing a file is printing a new receipt — 'w' replaces the old receipt, 'a' adds another line.
with open("log.txt", "w", encoding="utf-8") as f:
f.write("Session started\n")
with open("log.txt", "a", encoding="utf-8") as f:
f.write("User logged in\n")Python Delete Files
Use os.remove(path) to delete a file. os.path.exists() checks first.
For folders use shutil.rmtree — be careful, deletion is permanent.
Real-life example: Deleting a file is throwing a paper in the shredder — confirm before you do it.
import os
path = "temp.txt"
if os.path.exists(path):
os.remove(path)
print("Deleted")