File Handling — Insertion, Deletion, Updating Data
Python has no direct method to insert/delete/modify a line in the middle of a text file — because files are stored as a continuous byte stream. The standard approach is to read all content, modify it in memory, and rewrite the file (usually via a temporary file).
Updating (Modifying) a Line
# Suppose marks.txt contains:
# Riya,85
# Amit,70
# Zoya,90
with open("marks.txt", "r") as f:
lines = f.readlines()
# Update Amit's marks to 75
for i, line in enumerate(lines):
name, marks = line.strip().split(",")
if name == "Amit":
lines[i] = f"{name},75\n"
with open("marks.txt", "w") as f:
f.writelines(lines)
Inserting a Line at a Specific Position
with open("marks.txt", "r") as f:
lines = f.readlines()
lines.insert(1, "Karan,88\n") # insert a new line at index 1
with open("marks.txt", "w") as f:
f.writelines(lines)
Deleting a Line
with open("marks.txt", "r") as f:
lines = f.readlines()
lines = [line for line in lines if not line.startswith("Zoya")]
with open("marks.txt", "w") as f:
f.writelines(lines)
Using a Temporary File (safer for large files)
import os
def update_record(filename, target_name, new_line):
temp_file = filename + ".tmp"
with open(filename, "r") as infile, open(temp_file, "w") as outfile:
for line in infile:
if line.startswith(target_name):
outfile.write(new_line + "\n")
else:
outfile.write(line)
os.replace(temp_file, filename) # atomically replace original
update_record("marks.txt", "Riya", "Riya,95")
Updating a CSV file
import csv
with open("students.csv", "r") as f:
rows = list(csv.reader(f))
for row in rows:
if row[0] == "Amit":
row[1] = "23" # update age
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
Deleting a file entirely
import os
if os.path.exists("temp.txt"):
os.remove("temp.txt")
else:
print("File does not exist")
Summary — file "CRUD" via Python
| Operation | Approach |
|---|---|
| Create | open(file, 'w') or 'x' |
| Read | open(file, 'r') + read()/readlines() |
| Update | Read all → modify in memory → rewrite with 'w' |
| Delete (line) | Read all → filter out unwanted line(s) → rewrite |
| Delete (file) | os.remove(filename) |