📂 File Handling

File Handling

फाइल हैंडलिंग

⏱ 5 hr3 topicsInteractive
🎯 By the end: You can open files in the right mode, read and write text, use the with statement, pickle/unpickle binary data, and read/write CSV files.

So far our programs forget everything the moment they stop — variables live only in memory. File handling gives programs data persistence: the ability to save data to disk and read it back later. This is how real apps remember your settings, scores and records. CBSE expects three flavours: text files, binary files (with pickle), and CSV files.

The in-browser playground has no real filesystem, so the file examples here are shown as code to study and run in IDLE, Thonny or any Python on a computer. Read them carefully — file handling is heavily tested.

1Text files: open, read, write, with

Files come in two kinds: text files (human-readable characters, e.g. .txt) and binary files (raw bytes, e.g. images). You work with a file in three steps: open it, process it, then close it.

Opening: the access modes

ModeMeaning
rRead (default). Error if the file is missing.
wWrite — creates the file, or erases existing contents.
aAppend — adds to the end, keeps existing contents.
r+ / w+ / a+Read and write together.
f = open("notes.txt", "w")
f.write("Hello Vidaara\n")
f.close()           # always close!

The with statement (best practice)

The with statement opens a file and closes it automatically, even if an error occurs — so you never forget:

with open("notes.txt", "r") as f:
    data = f.read()      # whole file as one string
# file is closed automatically here

Reading and writing

  • read() — the whole file as a string; read(n) — n characters.
  • readline() — one line; readlines() — a list of all lines.
  • write(s) — write a string; writelines(list) — write a list of strings.
  • tell() — current file-pointer position; seek(n) — move the pointer to byte n.
Mode w erases the file's contents! Use a (append) when you want to keep what's already there.
Key points
  • Steps: open → process → close. The with statement closes the file automatically.
  • Modes: r (read), w (write, erases!), a (append), and the + variants for read+write.
  • Read: read(), readline(), readlines(). Write: write(), writelines(). Pointer: tell(), seek().

2Binary files with pickle

Binary files store raw bytes, not text — useful for saving whole Python objects (lists, dictionaries) directly. The pickle module does this through serialization: turning an object into a byte stream (pickling) and back (unpickling).

  • pickle.dump(object, file) — write (pickle) an object into a binary file.
  • pickle.load(file) — read (unpickle) an object back from a binary file.

Binary files must be opened in binary modes: rb (read binary), wb (write binary), ab (append binary):

import pickle

student = {"name": "Asha", "marks": 92}

# write (pickle) the dictionary
with open("data.dat", "wb") as f:
    pickle.dump(student, f)

# read (unpickle) it back
with open("data.dat", "rb") as f:
    record = pickle.load(f)
print(record["name"])    # Asha
Typical record operations on a binary file — insert, search, update, delete — all follow the same idea: load the records into a list, change the list in memory, then dump the whole list back.
Key points
  • Binary files store raw bytes; pickle serialises whole Python objects (lists, dicts).
  • pickle.dump(obj, f) writes (pickles); pickle.load(f) reads (unpickles).
  • Open binary files with rb / wb / ab.
  • Insert/search/update/delete records by loading them, changing the list, and dumping it back.

3CSV files

CSV (Comma-Separated Values) is a simple text format where each line is a row and values are separated by commas — the universal language of spreadsheets. Python's csv module handles it cleanly:

import csv

# WRITING
with open("marks.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Marks"])        # one row
    writer.writerows([["Asha", 92], ["Ravi", 85]])  # many rows

# READING
with open("marks.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)      # each row is a list of strings
  • csv.writer(f)writerow(list) writes one row; writerows(list_of_lists) writes many.
  • csv.reader(f) → loop over it to get each row as a list of strings.
  • You can change the separator with the delimiter argument (e.g. a tab or semicolon).
Use newline="" when opening a CSV for writing, to avoid blank lines appearing between rows on some systems.
Key points
  • CSV is plain text: rows on lines, values separated by commas — used by spreadsheets.
  • Writing: csv.writer(f) with writerow() (one row) and writerows() (many).
  • Reading: csv.reader(f), looped to give each row as a list of strings.
  • Open CSVs for writing with newline="" to avoid extra blank lines.

★ Practical: a notes saver (run on a computer)

On a real Python install (IDLE/Thonny), write programs that:

  1. Use with open(..."w") to write three lines to notes.txt, then read them back with readlines().
  2. Append a fourth line using mode 'a' and confirm the first three survive.
  3. Pickle a dictionary of marks to a .dat file, then unpickle and print it.
  4. Write a CSV of three students with writerows(), then read and print each row.

Ready for the chapter test?

Answer 5 questions. Score 60% or more to mark this chapter complete.

Start the test →

💡 Log in to save your progress and earn the certificate.