Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Unit 4 — File Handling: Insertion, Deletion, Updating Data

Lesson 49 of 50 in the free Python Programming notes on Siksha Sarovar, written by Rohit Jangra.

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

OperationApproach
Createopen(file, 'w') or 'x'
Readopen(file, 'r') + read()/readlines()
UpdateRead all → modify in memory → rewrite with 'w'
Delete (line)Read all → filter out unwanted line(s) → rewrite
Delete (file)os.remove(filename)