CS Pathfinder Logo CS Pathfinder


Unit 4 · Modules and File Handling

Text File Handling

Understand how to open, read, and manage text files in Python, including file modes, the with statement, and the file pointer concept.

Introduction

Files are the most common way to store data permanently. Unlike variables (which lose their values when the program ends), files retain data on disk. Python provides built-in functions for working with files without needing any external library.

File handling is essential for reading configuration files, processing data, saving user input, generating reports, and more. It is one of the most tested topics in university Python exams.

University Definition

File handling in Python refers to the process of reading from and writing to files stored on disk. A text file contains data as a sequence of characters (encoded in plain text), while a binary file contains data as a sequence of bytes. Python uses the built-in open() function to create file objects that provide methods for reading and writing.

Table of Contents

Text Files vs Binary Files

Feature Text File Binary File
Data Format Characters (human-readable) Bytes (not human-readable)
Extension .txt, .csv, .py, .html .bin, .dat, .jpg, .pdf
Line Ending Converted (\\n varies by OS) No conversion
Readable Yes (in any text editor) No (shows garbage characters)
Encoding UTF-8, ASCII, etc. Raw bytes

The open() and close() Functions

University Definition

The open() function opens a file and returns a corresponding file object. The syntax is: file_object = open(filename, mode). The close() method flushes any unwritten data and closes the file object, releasing system resources.

# Basic file opening and closing
f = open("data.txt", "r")   # Open for reading
content = f.read()          # Read the content
f.close()                   # Close the file

# Always close files to free resources
# But using 'with' is better (see next section)

File Modes

Mode Description File Must Exist?
r Read (default). Pointer at beginning. Yes — raises FileNotFoundError
w Write. Truncates (erases) existing content. No — creates new file
a Append. Pointer at end. Adds to existing content. No — creates new file
r+ Read and write. Pointer at beginning. Yes — raises FileNotFoundError
w+ Write and read. Truncates existing content. No — creates new file
a+ Append and read. Pointer at end. No — creates new file

University Exam Tip

Warning: "w" mode erases all existing content! Always double-check before using "w" mode. Use "a" to safely add content without erasing. This is the most common file handling mistake in exams.

The with Statement

The with statement automatically closes the file when the block ends, even if an exception occurs. This is the recommended way to handle files in Python.

# Without with (old way — risky)
f = open("data.txt", "r")
content = f.read()
f.close()   # Must remember to close!

# With statement (recommended way)
with open("data.txt", "r") as f:
    content = f.read()
# File is automatically closed here!

# Multiple files at once
with open("input.txt", "r") as fin, open("output.txt", "w") as fout:
    fout.write(fin.read())

University Definition

The with statement (context manager) ensures proper resource management by automatically closing files after the indented block finishes. This prevents resource leaks and is the Pythonic way to handle files.

The File Pointer

The file pointer is like a cursor that tracks the current position in the file. When you read or write, the pointer moves forward.

with open("sample.txt", "r") as f:
    print(f.tell())      # 0 (beginning of file)

    f.read(5)            # Read first 5 characters
    print(f.tell())      # 5 (pointer moved to position 5)

    f.read()             # Read rest of file
    print(f.tell())      # End of file

    f.seek(0)            # Move pointer back to beginning
    print(f.tell())      # 0 (back to start)

    print(f.readline())  # Reads the first line

Reading Methods

Method Description Returns
read() Read entire file Single string
read(n) Read n characters String of n chars
readline() Read one line (including \\n) Single string
readlines() Read all lines List of strings
# Sample file "data.txt" contains:
# Hello World
# Python Programming
# File Handling

with open("data.txt", "r") as f:
    # Method 1: read() — entire file as one string
    content = f.read()
    print(content)
    # Output:
    # Hello World
    # Python Programming
    # File Handling

with open("data.txt", "r") as f:
    # Method 2: readline() — one line at a time
    line1 = f.readline()   # "Hello World\n"
    line2 = f.readline()   # "Python Programming\n"
    print(line1.strip())   # "Hello World"
    print(line2.strip())   # "Python Programming"

with open("data.txt", "r") as f:
    # Method 3: readlines() — all lines as a list
    lines = f.readlines()
    print(lines)
    # ['Hello World\n', 'Python Programming\n', 'File Handling']

with open("data.txt", "r") as f:
    # Method 4: Iterate over lines (memory efficient)
    for line in f:
        print(line.strip())

Practical Examples

Example 1: Check if File Exists Before Opening

import os

filename = "data.txt"

if os.path.exists(filename):
    with open(filename, "r") as f:
        print(f.read())
else:
    print(f"File '{filename}' not found!")

# Alternative: use try-except
try:
    with open("data.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("File not found!")

Example 2: Write Data to a File

# Write to a file (creates new file or overwrites)
with open("output.txt", "w") as f:
    f.write("Hello, World!\n")
    f.write("Python File Handling\n")
    f.write("Module 4\n")

# Append to a file (adds to existing content)
with open("output.txt", "a") as f:
    f.write("This line is appended.\n")

Example 3: Count Lines, Words, and Characters

def count_file_stats(filename):
    with open(filename, "r") as f:
        content = f.read()
    lines = content.split("\n")
    words = content.split()
    chars = len(content)
    return len(lines), len(words), chars

lines, words, chars = count_file_stats("data.txt")
print(f"Lines: {lines}")
print(f"Words: {words}")
print(f"Characters: {chars}")

Key Points

open() returns a file object; always close files when done.

"r" mode requires the file to exist; "w" creates or overwrites.

"w" erases existing content; use "a" to append safely.

The with statement auto-closes files and is the recommended approach.

read() returns a string; readlines() returns a list of strings.

readline() reads one line at a time; iterating over file is memory-efficient.

The file pointer tracks the current position; use seek() to reposition.

Use try-except to handle FileNotFoundError gracefully.

Practice Questions

Q1: What is the difference between read(), readline(), and readlines()?

Answer: read() returns entire file as one string. readline() returns one line. readlines() returns a list of all lines.

Q2: What happens when you open a file with "w" mode?

Answer: It creates a new file if it doesn't exist, or completely erases the existing content if the file exists. The pointer starts at the beginning.

Q3: Why is the with statement preferred over manual open()/close()?

Answer: with automatically closes the file even if an exception occurs, preventing resource leaks and eliminating the need to remember close().

Q4: Write a program to count the number of lines in a text file.

Answer: with open("file.txt") as f: lines = len(f.readlines()); print(lines)

Q5: What is the difference between text files and binary files?

Answer: Text files store data as human-readable characters; binary files store data as raw bytes. Text files use encoding (UTF-8); binary files do not.

Summary

open() opens a file; close() closes it; with handles both automatically.

File modes: r (read), w (write/truncate), a (append), r+ (read+write).

Reading methods: read(), readline(), readlines().

The file pointer tracks position; use tell() and seek().

Always use with statement for safe file handling.

Handle FileNotFoundError using try-except or os.path.exists().

Python Programming Handwritten Notes

Master Python Programming with Easy Handwritten Notes – Perfect for Interviews, Placements, GATE & Exams.