Computer Science: Class 12 — Chapter 2: File Handling in Python

Introduction to Files & File Types

In Python, variables have a lifetime limited to the execution of the program. To store data permanently for future reusability, data must be written to secondary storage devices in the form of files. A file is a named location on a secondary storage medium where data is permanently stored.

Text Files vs. Binary Files

Computers store all files as sequences of bytes (0s and 1s). However, files are classified based on how these bytes are interpreted:

  • Text File : Consists of human-readable characters. Each character is translated from its binary representation using encoding schemes like ASCII or UNICODE . Lines are terminated by a special character called End of Line (EOL) , which is typically the newline character ( \n ) or carriage return ( \r\n ). Common extensions include .txt , .py , and .csv .
  • Binary File : Consists of raw byte streams that do not represent ASCII characters directly. Instead, they represent complex data structures, images, audio, video, or executable code. They are not human-readable and require specific software to interpret. A single-bit corruption can render the entire file unreadable. Common extensions include .dat , .png , and .exe .

Technical Profile: Data File Formats

  • Architecture Layer / Tier: Operating System File System & Application Layer
  • Operational Mechanics & Syntax: Text files undergo character-to-byte translation during read/write operations. Binary files bypass translation, writing raw memory buffers directly to disk.
  • System Trade-offs & Failures: Text files have higher storage overhead due to character encoding (e.g., a .docx file contains extensive metadata compared to a raw .txt file). Binary files are highly compact and fast but lack interoperability and are highly susceptible to corruption.
Core Computer Science Concept Technical Definition / Operational State Structural Parameters & Specifications Computational Function & System Purpose
Text File A sequence of characters stored as encoded bytes. Uses EOL ( \n ) to demarcate lines; translated via ASCII/UNICODE. Human-readable configuration, scripting, and structured data exchange.
Binary File A raw stream of bytes representing direct memory states. No line terminators; requires specific application-level parsers. High-performance storage of multimedia, compiled code, and serialized objects.
Opening and Closing a Text File

To perform any operation on a file, it must first be opened to establish a link between the program and the file on secondary storage. Once operations are complete, the file must be closed to free system resources.

The open() Function & File Objects

The built-in open() function creates a file object (also known as a file handle) that acts as a pipeline for data transfer.

  
  file_object = open(file_name, access_mode)

The file object exposes several key attributes:

  • file_object.closed : Returns True if the file is closed, False otherwise.
  • file_object.mode : Returns the access mode in which the file was opened.
  • file_object.name : Returns the name of the file.
File Access Modes

The access mode determines the permitted operations (reading, writing, appending) and the initial position of the file pointer (offset).

File Mode Description File Offset Position
<r> Opens the file in read-only mode (default). Raises FileNotFoundError if the file does not exist. Beginning of the file
<rb> Opens the file in binary and read-only mode. Beginning of the file
<r+> or <+r> Opens the file in both read and write mode. Beginning of the file
<w> Opens the file in write-only mode. Overwrites existing contents. Creates a new file if it does not exist. Beginning of the file
<wb+> or <+wb> Opens the file in read, write, and binary mode. Overwrites existing contents. Beginning of the file
<a> Opens the file in append mode. Appends data to the end of the file. Creates a new file if it does not exist. End of the file
<a+> or <+a> Opens the file in append and read mode. End of the file
Closing Files & The with Clause

Closing a file is critical to flush unwritten data from the buffer to the disk and release system locks. This can be done explicitly using the close() method, or implicitly using the with statement (context manager).

  
    # Explicit closing
    file_object = open("myfile.txt", "r")
    content = file_object.read()
    file_object.close()
    # Implicit closing using 'with' (Recommended)
    with open("myfile.txt", "r") as file_object:
    content = file_object.read()
  
Reading and Writing Operations

Python provides distinct methods to read from and write to \text files, handling data either as single strings or sequences of strings.

Writing Methods
  • write(string) : Writes a single string to the file. It returns the number of characters written. Note that numeric data must be explicitly converted to a string using str() before writing.
  • writelines(iterable) : Writes a sequence of strings (such as a list or tuple) to the file. It does not automatically append newlines; they must be explicitly included in the strings.
  • flush() : Forcefully writes any buffered data to the file on disk without closing the file.
  
    # Example of writing to a file
    with open("myfile.txt", "w") as f:
    f.write("Hey I have started using files in Python\n")
    lines = ["Hello everyone\n", "Writing multiline strings\n"]
    f.writelines(lines)
  
Reading Methods
  • read(n) : Reads up to n characters from the file. If n is omitted or negative, it reads the entire file.
  • readline(n) : Reads a single line from the file, up to the newline character. If n is specified, it reads at most n characters from the current line.
  • readlines() : Reads all lines from the file and returns them as a list of strings, with each string ending in a newline character ( \n ).
  
    # Example of reading from a file
    with open("myfile.txt", "r") as f:
    # Read first 10 characters
    print(f.read(10))
    # Reset pointer and read line-by-line
    f.seek(0)
    for line in f:
    print(line.strip())
  
File Offsets & Random Access

By default, file access is sequential. To access data in a random fashion, Python provides methods to query and manipulate the file pointer's position.

The tell() and seek() Methods
  • tell() : Returns an integer representing the current byte position of the file pointer from the beginning of the file.
  • seek(offset, reference_point) : Moves the file pointer by offset bytes relative to the position specified by reference_point .

The reference_point parameter can take one of three values:

  • 0 : Beginning of the file (default). Supported in both \text and binary modes.
  • 1 : Current position of the file pointer. In \text mode, only an offset of 0 is allowed.
  • 2 : End of the file. In \text mode, only an offset of 0 is allowed.
  
    # Example of seek and tell
    with open("testfile.txt", "r+") as f:
    print("Initial position:", f.tell())
    content = f.read(10)
    print("Position after reading 10 bytes:", f.tell())
    f.seek(0)
    print("Position after seek(0):", f.tell())
  
The Pickle Module (Binary Serialization)

Python objects (lists, dictionaries, custom class instances) exist only in memory during execution. To save these complex structures to a file and reconstruct them later, Python provides the pickle module.

Serialization vs. Deserialization
  • Serialization (Pickling) : The process of converting a Python object structure into a byte stream to be written to a binary file.
  • Deserialization (Unpickling) : The inverse process, where a byte stream from a binary file is converted back into a live Python object.

Technical Profile: pickle Module

  • Architecture Layer / Tier: Python Standard Library Serialization Engine
  • Operational Mechanics & Syntax:
    • pickle.dump(obj, file_obj) : Serializes obj and writes it to the binary file file_obj (must be opened in wb or ab mode).
    • pickle.load(file_obj) : Reads a serialized byte stream from file_obj (must be opened in rb mode) and reconstructs the original Python object.
  • System Trade-offs & Failures: Pickling is Python-specific; pickled files cannot be easily read by other languages (like Java or C++). Loading untrusted pickled data is a major security risk as it can execute arbitrary code.
Implementation Case Study: Employee Record System

A system is required to accept employee records (ID, Name, Salary, Allowances) from a user, calculate total salary, write them to a binary file, and subsequently read and display all records.


Socio-Technical Analysis & Core Systemic Impact:

The implementation uses a binary file ( empfile.dat ) opened in append-binary ( ab ) mode to store records as serialized lists. Reading is performed in a while True loop inside a try...except EOFError block, which gracefully handles the end-of-file condition when pickle.load() attempts to read past the last record.

  
    import pickle
    # Writing records
    with open("empfile.dat", "wb") as bfile:
    record = [101, "D N Ravi", 32600, 4400, 37000]
    pickle.dump(record, bfile)
    # Reading records
    try:
    with open("empfile.dat", "rb") as bfile:
    while True:
    data = pickle.load(bfile)
    print("Record:", data)
    except EOFError:
    print("End of file reached successfully.")