Follow Us
माध्यम चुनें / Select Medium:
Eng (English) Hindi (हिन्दी)
CBSE • कक्षा XII • Computer Science • अध्याय 2
अनुमानित समय: 45 Mins
प्रगति: अध्ययनरत

पायथन में फाइल हैंडलिंग (File Handling)

In CBSE Class 12 Computer Science, "File Handling in Python" provides an exhaustive master resource on non-volatile data persistence. This comprehensive chapter covers text files (`.txt`), binary files (`.dat`), and structured CSV files (`.csv`), file access modes (`r`, `w`, `a`, `r+`, `w+`, `a+`, `rb`, `wb`, `ab`), safe file opening via context managers (`with open() as f:`), file pointer manipulation (`seek()` and `tell()`), binary object serialization using the `pickle` module (`dump()`, `load()`), and tabular manipulation using the standard `csv` library aligned with the 2026–27 CBSE curriculum.

What Happens to Your Program's Data When the Power Plugs Are Pulled?

When your Python program runs, every variable, list, and dictionary is stored in volatile semiconductor RAM. The instant your program terminates or your computer loses power, every byte in RAM vanishes into thin air. To build real-world software—like video game save files, bank transaction logs, student report card databases, and machine learning model checkpoints—data must be permanently written to non-volatile secondary storage (SSDs or Hard Disks). How does a Python script create, read, search, and update persistent files on an operating system disk without corrupting the file system? This chapter masters the three pillars of file persistence: Text, Binary, and CSV files.

यह अध्याय क्यों महत्वपूर्ण है

File I/O is the universal gateway through which software interacts with the outside world. Whether you are parsing server logs, loading gigabyte-scale datasets for data science, saving serialized game states with pickle, or exporting financial audit reports in CSV format for Microsoft Excel, file handling is an everyday requirement for every software developer. Understanding buffer flushes, stream encodings, and the `with open()` context manager prevents catastrophic resource leaks and corrupted data files.

अध्ययन से पूर्व (आवश्यक ज्ञान)

  • Python string indexing, slicing, and string manipulation methods.
  • Lists, tuples, and dictionary collection operations.
  • Exception handling (`try-except`) for handling `FileNotFoundError` and `EOFError`.

इस अध्याय के लक्ष्य

  • Differentiate between Text Files (human-readable ASCII/UTF-8), Binary Files (raw serialized byte streams), and CSV Files.
  • Master all standard File Access Modes: `r`, `w`, `a`, `r+`, `w+`, `a+`, and binary variants (`rb`, `wb`, `ab`).
  • Implement automated resource cleanup using the `with open(...) as file_handle:` context manager.
  • Read text files using `read()`, `readline()`, and `readlines()`, and write using `write()` and `writelines()`.
  • Manipulate the file cursor position using `tell()` (current offset) and `seek(offset, whence)` (cursor repositioning).
  • Serialize and deserialize Python objects using `pickle.dump()` and `pickle.load()` with `EOFError` handling.
  • Read and write structured tabular data using Python's built-in `csv.reader()` and `csv.writer()`.

अध्याय रूपरेखा एवं प्रगति

1 1. The Three File Types & Access Mo...
2 2. Text File Operations & File Poin...
3 3. Binary File Processing with the...
4 4. Tabular CSV Processing with the...

सम्पूर्ण सैद्धांतिक एवं वैचारिक अध्ययन

1. The Three File Types & Access Modes Matrix

Understand

In Python, files on secondary storage are categorized into three distinct formats:

  • Text Files (`.txt`): Stored as a sequence of human-readable ASCII or UTF-8 encoded characters. Each line terminates with an End-of-Line (EOL) character (usually `\n` on Linux/macOS, `\r\n` on Windows), which Python automatically translates to standard `\n`.
  • Binary Files (`.dat`, `.bin`): Raw binary byte streams directly mirroring memory representations without character translation or EOL delimiters. Used for images, audio, compiled executables, and serialized Python objects.
  • CSV Files (`.csv`): Comma-Separated Values text files storing tabular records where fields are delimited by commas (or tabs/semicolons).
The Complete File Access Modes Matrix
ModeTypeFile Pointer PositionBehavior if File ExistsBehavior if File Missing
`'r'` / `'rb'`Read OnlyBeginning (Offset 0)Opens for reading.Raises `FileNotFoundError`!
`'w'` / `'wb'`Write OnlyBeginning (Offset 0)TRUNCATES (erases) entire file to 0 bytes!Creates a brand-new file.
`'a'` / `'ab'`Append OnlyEnd of FilePreserves existing data; appends new data at end.Creates a brand-new file.
`'r+'` / `'rb+'`Read & WriteBeginning (Offset 0)Opens for reading and in-place overwriting.Raises `FileNotFoundError`!
`'w+'` / `'wb+'`Write & ReadBeginning (Offset 0)Truncates file to 0 bytes, then allows read/write.Creates a brand-new file.
`'a+'` / `'ab+'`Append & ReadEnd of FilePreserves existing data; writes strictly append to end.Creates a brand-new file.

2. Text File Operations & File Pointer Positioning

Understand
The Modern Standard: Context Manager (`with open()`)

Never call raw `f.close()` in production code. The with open() as f: context manager automatically closes the file and flushes OS buffers even if an unhandled exception or return occurs:

# Writing to a text file:
with open("students.txt", "w", encoding="utf-8") as f:
    f.write("Roll,Name,Marks\n")
    f.writelines(["1,Aarav,95\n", "2,Sneha,98\n", "3,Rohan,88\n"])

# Reading methods comparison:
with open("students.txt", "r", encoding="utf-8") as f:
    # 1. f.read(n): Reads n characters (or all characters if n omitted)
    # 2. f.readline(): Reads a single line including the '\n'
    # 3. f.readlines(): Reads all lines into a LIST of strings
    lines = f.readlines()
    print(lines) # ['Roll,Name,Marks\n', '1,Aarav,95\n', ...]
Manipulating the File Pointer: `tell()` and `seek()`
  • `f.tell()`: Returns the current byte offset of the file pointer from the beginning of the file.
  • `f.seek(offset, whence=0)`: Moves the file pointer to a new position:
    • `whence = 0` (Default): `offset` is calculated from the beginning of the file (SEEK_SET).
    • `whence = 1`: `offset` is relative to the current pointer position (SEEK_CUR) (binary files only!).
    • `whence = 2`: `offset` is relative to the end of the file (SEEK_END) (e.g., `f.seek(0, 2)` jumps to end).

3. Binary File Processing with the `pickle` Module

Understand & Deep Dive

Pickling (Serialization): Converting a live in-memory Python object hierarchy (list, dictionary, custom class) into a raw byte stream for storage on disk. Unpickling (Deserialization): Reconstructing the original Python object from the byte stream.

OperationFunction SignatureFile Mode Required
Serialization (Pickling)`pickle.dump(object, file_handle)``'wb'` or `'ab'`
Deserialization (Unpickling)`pickle.load(file_handle)``'rb'`
Complete Binary File Read-Write Template with `EOFError` Handling:
import pickle

# Writing serialized student records:
records = [
    {"roll": 101, "name": "Aarav", "marks": 94.5},
    {"roll": 102, "name": "Sneha", "marks": 98.0}
]
with open("students.dat", "wb") as f:
    for rec in records:
        pickle.dump(rec, f)

# Reading serialized binary records sequentially:
with open("students.dat", "rb") as f:
    try:
        while True:
            student = pickle.load(f)  # Unpickles next object
            print(f"Roll: {student['roll']} | Name: {student['name']} | Marks: {student['marks']}")
    except EOFError:
        # Standard idiom: pickle.load() raises EOFError when file ends!
        print("End of binary file reached successfully.")

4. Tabular CSV Processing with the `csv` Module

Understand

Python's built-in csv library standardizes reading and writing comma-separated tabular files:

import csv

# Writing to CSV (newline='' prevents blank lines on Windows!):
with open("scores.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f, delimiter=",")
    writer.writerow(["Roll", "Name", "Physics", "Chemistry"])  # Header
    writer.writerows([
        [101, "Aarav", 95, 92],
        [102, "Sneha", 98, 96]
    ])

# Reading from CSV:
with open("scores.csv", "r", encoding="utf-8") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row) # ['101', 'Aarav', '95', '92'] (Each row is a list of strings!)

प्रोग्रामिंग सिंटेक्स, स्टेटमेंट्स एवं भाषा अनुवादक नियम

Seek Pointer Calculation
$$\text{New Pos} = \text{Reference}(\text{whence}) + \text{offset}$$
whence: 0=Start, 1=Current, 2=End.
EOF Detection Law
$$\text{pickle.load}(f) \to \text{EOFError} \iff f.\text{tell}() == \text{File Size}$$
End-of-file condition in binary unpickling loops.

File Handling Architecture & Pickling Pipeline

Python File Persistence Architecture: Text, Binary & CSV In-Memory RAM Python Objects dict, list, str (Volatile) pickle.dump() (Serialization) pickle.load() (Deserialization) Secondary Storage (Disk) • Binary (.dat): Byte stream (pickle) • Text (.txt): ASCII/UTF-8 with EOL (\n) • CSV (.csv): Tabular rows & delimiters File Pointer Control: tell() & seek(offset, whence) whence=0 (Beginning of File) whence=1 (Current Position) whence=2 (End) • f.tell(): Returns current 0-based byte offset of the cursor from file start. • f.seek(0, 0): Rewinds pointer to start; f.seek(0, 2): Jumps directly to end of file.

अध्याय का सार संक्षेप एवं 10 मुख्य निष्कर्ष

मुख्य बिंदु 1
Text files store human-readable characters with EOL character translations; binary files store raw bytes without translation.
मुख्य बिंदु 2
File access mode `w` truncates existing files to 0 bytes; mode `a` appends data to the end without truncation.
मुख्य बिंदु 3
Opening a missing file in mode `r` raises a `FileNotFoundError`; modes `w` and `a` create a new file automatically.
मुख्य बिंदु 4
The `with open() as f:` context manager guarantees automatic file closure and OS buffer flushing under all execution paths.
मुख्य बिंदु 5
`read()` returns all or $n$ characters as a string; `readline()` reads a single line; `readlines()` returns a list of line strings.
मुख्य बिंदु 6
`f.tell()` returns the current byte offset of the file pointer; `f.seek(offset, whence)` repositions the pointer.
मुख्य बिंदु 7
The `pickle` module serializes Python objects to binary byte streams via `dump()` and deserializes them via `load()`.
मुख्य बिंदु 8
In binary file processing, reading past the end of the file with `pickle.load()` raises an `EOFError`.
मुख्य बिंदु 9
CSV files store tabular data separated by delimiters (commas); processed using `csv.reader()` and `csv.writer()`.
मुख्य बिंदु 10
When opening CSV files for writing on Windows, `newline=""` must be passed to prevent unwanted blank lines between rows.

स्व-मूल्यांकन अभ्यास (Check Your Understanding)

मूल वैचारिक स्पष्टता की जांच के लिए नैदानिक प्रश्न। पहले स्वयं हल करें, फिर उत्तर देखें।

1
Differentiate between Text Files and Binary Files based on internal data storage, character translation, and file extension.
उत्तर एवं व्याख्या देखें
उत्तर: • Text Files (`.txt`, `.csv`): Store data as human-readable Unicode/ASCII characters. Translates platform-specific End-of-Line characters (e.g., converting `\r\n` on Windows to `\n` in Python).
• Binary Files (`.dat`, `.bin`, `.png`): Store raw bytes directly mirroring in-memory binary representations without any translation or EOL delimiters. Cannot be read in standard text editors without hex decoders.
Text files use character encoding and EOL translation; binary files store raw unencoded bytes.
2
Explain the difference between file access modes `w`, `w+`, `a`, and `r+`. What happens to existing data in each mode?
उत्तर एवं व्याख्या देखें
उत्तर: • `w`: Write-only mode. Erases (truncates) existing content completely. Pointer at start.
• `w+`: Write and Read mode. Also erases existing content completely. Allows reading back newly written data.
• `a`: Append-only mode. Preserves existing content; all writes strictly append at the end of the file.
• `r+`: Read and Write mode. Preserves existing content; pointer starts at offset 0, allowing in-place overwriting of existing bytes without truncating the file.
w and w+ truncate to 0; a and r+ preserve data. r+ starts at beginning; a starts at end.
3
Why is the `with open(...) as f:` syntax strongly recommended over manual `open()` and `f.close()` in Python?
उत्तर एवं व्याख्या देखें
उत्तर:

The with statement implements Python's context management protocol (enter and exit magic methods). It guarantees that the file handle is automatically and cleanly closed as soon as the execution leaves the with block—even if an unhandled exception crashes the block or an abrupt return or break is executed. Manual close() is frequently skipped when errors occur, leading to resource leaks, file locks, and corrupted disk buffers.


Guarantees automatic file closure and buffer flushing even during exceptions.
4
What is the purpose of `seek()` and `tell()` methods? Explain the meaning of the `whence` parameter in `seek(offset, whence)`.
उत्तर एवं व्याख्या देखें
उत्तर:

• tell() returns the current byte position of the file pointer from the beginning of the file.
• seek(offset, whence) moves the file pointer to a new position. The whence parameter specifies the reference point:
- whence = 0: Offset is calculated from the beginning of the file (SEEK_SET).
- whence = 1: Offset is calculated from the current pointer position (SEEK_CUR).
- whence = 2: Offset is calculated from the end of the file (SEEK_END).


tell() gets current position; seek() moves pointer. whence: 0=start, 1=current, 2=end.
5
What is pickling and unpickling? Write a Python function to write a dictionary containing employee data to a binary file `emp.dat`.
उत्तर एवं व्याख्या देखें
उत्तर: Pickling is the process of serializing a Python object into a byte stream. Unpickling is the inverse process of deserializing a byte stream back into a Python object.
Code:
import pickle
def save_employee(emp_data):
    with open("emp.dat", "wb") as f:
        pickle.dump(emp_data, f)

emp = {"id": 101, "name": "Vikas", "salary": 75000}
save_employee(emp)

Use pickle.dump(obj, f) in "wb" mode to write binary serialized data.
6
How is the end of a binary file detected during unpickling with `pickle.load()`? Provide the standard loop structure.
उत्तर एवं व्याख्या देखें
उत्तर: Unlike text files where `readline()` returns an empty string `""` at EOF, `pickle.load()` raises an EOFError when it attempts to read past the end of the file. The standard idiom is an infinite `while True:` loop wrapped inside a `try-except EOFError:` block:
import pickle
with open("data.dat", "rb") as f:
    try:
        while True:
            record = pickle.load(f)
            print(record)
    except EOFError:
        pass  # File read complete!

Detect EOF in binary files by catching EOFError inside a while True loop.
7
Why is `newline=""` specified when opening a CSV file for writing using Python's `csv` module on Windows?
उत्तर एवं व्याख्या देखें
उत्तर: On Windows, standard text files terminate lines with carriage return and line feed (`\r\n`). The `csv.writer` module internally emits standard `\r\n` line endings by default. If `newline=""` is omitted, Python's text stream translation layer converts each `\n` into an additional `\r\n`, resulting in `\r\r\n` and generating an unwanted blank empty row after every single record in the resulting CSV file.
Prevents double carriage-return translation that creates blank lines on Windows.
8
Write a Python program to count the total number of lines, words, and characters in an existing text file `sample.txt`.
उत्तर एवं व्याख्या देखें
उत्तर:
with open("sample.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    num_lines = len(lines)
    num_words = sum(len(line.split()) for line in lines)
    num_chars = sum(len(line) for line in lines)
print(f"Lines: {num_lines}, Words: {num_words}, Characters: {num_chars}")

Use len(lines) for lines, line.split() for words, and len(line) for characters.
अध्याय का अध्ययन पूर्ण हुआ?
अभ्यास के लिए तैयार?

ऑनलाइन CBT टेस्ट देकर तैयारी का मूल्यांकन करें

झारखण्ड बोर्ड परीक्षा पैटर्न पर आधारित बहुविकल्पीय प्रश्नों का ऑनलाइन टेस्ट दें। तुरंत परिणाम, समय विश्लेषण और प्रत्येक प्रश्न का विस्तृत हल प्राप्त करें।

AI अध्ययन मित्र

त्वरित शंका समाधान

पायथन में फाइल हैंडलिंग (File Handling) में कोई संदेह या प्रश्न है? हमारे AI अध्ययन मित्र से तुरंत समझें।