Class 12 Computer Science Chapter 05A ยท 27 min read

๐Ÿ—‚๏ธ File Handling in Python (Text File)

Unit 1 ยท Ch 5A Nov 02, 2026
Chapter Quiz Share

๐Ÿ—‚๏ธ Give Your Program a Permanent Memory!

Imagine writing brilliant answers in your head during an exam โ€” and forgetting everything the moment you step out! That's exactly what happens to Python variables when a program ends. Files are your program's permanent memory โ€” data that survives power cuts, reboots, and program crashes!


5.1

Introduction

Why programs need files โ€” temporary RAM vs permanent disk storage

PersistenceStorage
5.2

Data Files

Text files vs Binary files โ€” what's the difference?

TextBinaryASCII
5.3

Open & Close

The open() and close() functions โ€” the lifecycle of a file

open()close()modes
5.4

Text File Operations

read, readline, readlines, write, writelines, flush, seek, tell

All text file methods
5.5

Standard Streams

stdin, stdout, stderr โ€” the three invisible data channels

sys moduleredirection

๐ŸŒŸ 5.1 Introduction โ€” Why Do We Need Files?

Every time your Python program runs, it creates variables, lists, dictionaries โ€” all stored in RAM (Random Access Memory). RAM is fast but temporary. The instant your program ends:

ALL DATA IS GONE. ๐Ÿ’จ

This is a massive problem for real-world applications. Imagine:

  • A school management system that forgets all student names every evening ๐Ÿ˜ฑ
  • A game that resets your score every time you restart ๐ŸŽฎ
  • A bank that loses all account balances after closing time ๐Ÿ’ธ

Files solve this problem! They store data permanently on the hard disk (secondary storage), which keeps data even without power.

๐Ÿง  Memory Trick

Think of RAM as a whiteboard in your classroom โ€” easy to write on, but erased at the end of class. Think of Files as your notebook โ€” permanent, portable, always there when you need it! ๐Ÿ““

What Can Files Do for Us?

  • ๐Ÿ’พ Persist data โ€” Save program output for future use
  • ๐Ÿ“– Read stored data โ€” Load previously saved information
  • ๐Ÿ”„ Share data โ€” One program writes, another reads
  • ๐Ÿ“Š Handle huge data โ€” Process data too large to fit in RAM (databases, logs, etc.)

๐Ÿ—‚๏ธ 5.2 Data Files โ€” Two Flavours!

Python supports two main types of data files. Choosing the right type matters!

  • ๐Ÿ“„ Text Files

    • Stores data as human-readable characters (ASCII or Unicode encoding)
    • Each line is separated by a newline character \n (Python adds/reads this automatically)
    • Can be opened and read in Notepad, VS Code, any text editor
    • Common extensions: .txt, .csv, .py, .html, .json
    • Example: Your Python source code .py file is itself a text file!
  • ๐Ÿ”’ Binary Files

    • Stores data as raw bytes โ€” exactly as it exists in RAM
    • Not human-readable; opening in Notepad shows garbage characters
    • No special newline handling โ€” data is read/written byte by byte
    • Common extensions: .jpg, .mp3, .exe, .pkl, .db
    • Example: A .jpg photo, an .mp3 song, a compiled .exe program
๐Ÿ“‹ Board Exam Hotspot

A standard question โ€” "Differentiate between text and binary files." Key differences:

  • Text files store data as characters; binary files store data as bytes
  • Text files are human-readable; binary files are not
  • Text files use \n as line separator; binary files have no such concept
  • Text files may undergo newline translation by the OS; binary files are read/written as-is

๐Ÿ“‚ 5.3 Opening and Closing Files

๐Ÿ”‘ The open() Function โ€” Your Master Key!

Before you can do anything with a file โ€” reading, writing, appending โ€” you must first open it using Python's built-in open() function. It returns a file object (also called a file handle) that you use for all subsequent operations.

๐Ÿ”‘ Syntax

file_object = open(filename, mode)
  • filename โ†’ Name (or full path) of the file as a string
  • mode โ†’ A string specifying how you want to open the file
  • Returns a file object for performing read/write operations

๐ŸŽญ 5.3.1 Opening Files โ€” File Modes Explained

The mode parameter is the most important argument to open(). It tells Python whether you want to read, write, or append โ€” and whether to create a new file or use an existing one.

  • 'r' โ€” Read Mode (Default) ๐Ÿ“–

    • Opens file for reading only โ€” cannot write
    • File must already exist โ€” raises FileNotFoundError if not found
    • File pointer is placed at the beginning of the file
    • Example: f = open("notes.txt", "r")
  • 'w' โ€” Write Mode (Dangerous!) โœ๏ธ

    • Opens file for writing only โ€” cannot read
    • Creates a new file if it doesn't exist
    • โš ๏ธ DESTROYS existing content if the file already exists โ€” no warning!
    • File pointer placed at the beginning (of the now-empty file)
    • Example: f = open("output.txt", "w")
  • 'a' โ€” Append Mode (Safe Writing) โž•

    • Opens file for writing at the end โ€” adds new content after existing content
    • Creates a new file if it doesn't exist
    • Preserves existing content โ€” safe for adding new records
    • File pointer placed at the end of the file
    • Example: f = open("diary.txt", "a")
  • 'r+' โ€” Read + Write Mode ๐Ÿ”€

    • Opens file for both reading AND writing
    • File must already exist โ€” raises FileNotFoundError if not
    • File pointer placed at the beginning โ€” can overwrite existing content
    • Example: f = open("data.txt", "r+")
  • 'w+' โ€” Write + Read Mode ๐Ÿ†•

    • Opens file for both reading AND writing
    • Creates file if not found; overwrites content if file exists
    • Example: f = open("data.txt", "w+")
  • 'a+' โ€” Append + Read Mode ๐Ÿ“Ž

    • Opens file for both reading AND appending
    • Creates file if not found; preserves existing content
    • Write pointer always at end; can seek to read from anywhere
    • Example: f = open("log.txt", "a+")
โš  Common Mistake

The difference between 'w' and 'a' is a common source of mistakes. Use 'w' only when you want to start fresh (it erases everything!). Use 'a' when you want to add new content to an existing file without losing old data. ๐Ÿšจ

๐Ÿ’ก Study Strategy

Use this rhyme to remember:

  • r = Read what's there (file must exist!)
  • w = Wipe clean, then Write (dangerous โ€” erases!)
  • a = Add to the end (always safe!)

๐Ÿ—บ๏ธ The File Lifecycle โ€” Open โ†’ Use โ†’ Close

flowchart TD
    A["๐Ÿš€ START\nProgram needs file access"]
    B["open(filename, mode)\nSpecify what and how"]
    C["File Object Created โœ…\nPointer positioned at start/end"]
    D["Perform Operations\nread() / write() / append()"]
    E["close()\nFlush buffer & release file"]
    F["๐Ÿ END\nData safely saved to disk"]
    ERR["โš ๏ธ FileNotFoundError!\nHandle with try-except"]

    A --> B
    B -->|"File found /\nFile created"| C
    B -->|"File missing\n(in r / r+ mode)"| ERR
    C --> D
    D --> E
    E --> F
    ERR -->|"Fix path or\ncreate file first"| A

    classDef normalNode fill:none;
    classDef tryNode fill:none;
    classDef exceptNode fill:none;
    classDef elseNode fill:none;

    class A normalNode;
    class B normalNode;
    class C elseNode;
    class D tryNode;
    class E normalNode;
    class F normalNode;
    class ERR exceptNode;

๐Ÿ”’ 5.3.2 Closing Files โ€” close()

After all file operations, always close the file! Leaving a file open is like leaving your exam paper on the desk without submitting it. Closing ensures:

  • โœ… All buffered data is flushed (written) to the actual disk file
  • โœ… The file is released โ€” other programs or users can now access it
  • โœ… System resources (file handles) are freed โ€” important in large programs
  • โœ… Data integrity is maintained โ€” no corruption from abrupt termination
๐Ÿ”‘ Syntax

file_object.close()
# Standard open โ†’ use โ†’ close pattern
f = open("story.txt", "r")
content = f.read()
print(content)
f.close()      # ๐Ÿ”’ Always close!
# ๐ŸŒŸ BEST PRACTICE โ€” The 'with' Statement (Context Manager)
# Automatically closes the file, even if an error occurs inside!
with open("story.txt", "r") as f:
    content = f.read()
    print(content)
# File is automatically closed here โ€” no f.close() needed!
print("File is now closed:", f.closed)   # True
๐Ÿ“‹ Board Exam Hotspot

The with statement is the preferred way to handle files because it guarantees the file is closed even if an exception occurs inside the block. The as f part gives the file object the name f.


๐Ÿ“– 5.4 Working with Text Files

Now the real fun begins! ๐ŸŽ‰ Let's explore all the operations you can perform on text files.


๐Ÿ” 5.4.1 Reading from Text Files

Python gives you three distinct methods to read from a text file. Each suits a different situation.

Assume our file poem.txt contains:

Roses are red,
Violets are blue,
Python is awesome,
And so are you!
  • read() โ€” Devour the Entire File at Once ๐Ÿ“œ

    • f.read() โ†’ Reads the complete file content as a single string
    • f.read(n) โ†’ Reads exactly n characters from current position
    • Returns an empty string "" when the end of file is reached
    • โš ๏ธ Careful with very large files โ€” loads everything into RAM!
  • readline() โ€” One Line at a Time ๐Ÿ“ƒ

    • Reads and returns one line, including its \n at the end
    • Returns an empty string "" when end of file is reached (not None!)
    • Memory efficient โ€” great for processing huge files line by line
    • Each call automatically advances the pointer to the next line
  • readlines() โ€” All Lines as a Python List ๐Ÿ“‹

    • Returns a list of strings โ€” each element is one complete line
    • Each string in the list includes its \n character
    • Access specific lines by index: lines[0], lines[2], etc.
    • Great when you need random access to specific line numbers
# โ”€โ”€ Method 1: read() โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
f = open("poem.txt", "r")
content = f.read()          # One big string
print(content)
f.close()
# Output:
# Roses are red,
# Violets are blue,
# Python is awesome,
# And so are you!
# โ”€โ”€ Method 1b: read(n) โ€” Read only n characters โ”€โ”€โ”€โ”€โ”€โ”€โ”€
f = open("poem.txt", "r")
first5 = f.read(5)          # Read first 5 chars
print(repr(first5))         # 'Roses'
next5 = f.read(5)           # Read next 5 chars
print(repr(next5))          # ' are '
f.close()
# โ”€โ”€ Method 2: readline() โ€” One line at a time โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
f = open("poem.txt", "r")
line1 = f.readline()
line2 = f.readline()
print(repr(line1))   # 'Roses are red,\n'
print(repr(line2))   # 'Violets are blue,\n'
f.close()
# โ”€โ”€ Method 3: readlines() โ€” Full list โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
f = open("poem.txt", "r")
all_lines = f.readlines()
print(all_lines)
# ['Roses are red,\n', 'Violets are blue,\n',
#  'Python is awesome,\n', 'And so are you!']
print("Line 3:", all_lines[2].strip())   # Python is awesome,
f.close()
# โ”€โ”€ ๐ŸŒŸ GOLD METHOD: Loop directly over file โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Most Pythonic! Memory efficient. No need for readlines()
f = open("poem.txt", "r")
for line in f:
    print(line, end="")    # end="" prevents double newline
f.close()
๐Ÿ“‹ Board Exam Tip
Board Exam Hotspot โ€” The Classic Comparison Question: Method Returns Reads
read() One string Entire file
read(n) One string n characters
readline() One string One line
readlines() A list of strings All lines
โš  Common Mistake

When printing lines from a file, each line already ends with \n. Using print(line) adds another \n (since print itself adds one), resulting in double spacing. Fix this with print(line, end="") or print(line.strip()).


โœ๏ธ 5.4.2 Writing onto Text Files

Two methods for writing content into text files:

  • write(string) โ€” Write a Single String โœ๏ธ

    • Takes exactly one string argument
    • Does NOT add newline automatically โ€” you must include \n yourself!
    • Returns an integer โ€” the number of characters written
    • Writes from the current file pointer position
  • writelines(list) โ€” Write a Sequence of Strings ๐Ÿ“

    • Accepts a list (or any iterable) of strings
    • Writes all strings one after another โ€” no separators added!
    • Does NOT add newlines between items โ€” include \n in each string!
    • Returns None
# โ”€โ”€ write() โ€” Manual newlines โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
f = open("results.txt", "w")
f.write("Class 12 Computer Science\n")
f.write("Chapter 6: File Handling\n")
chars = f.write("Topic: Writing to Files")   # No \n at end
print("Characters written:", chars)          # 23
f.close()
# File content:
# Class 12 Computer Science
# Chapter 6: File Handling
# Topic: Writing to Files
# โ”€โ”€ writelines() โ€” Write a list โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
f = open("students.txt", "w")
students = [
    "Aman Sharma\n",      # \n included in each string!
    "Priya Singh\n",
    "Rohan Gupta\n",
    "Sneha Joshi\n"
]
f.writelines(students)
f.close()
# File content:
# Aman Sharma
# Priya Singh
# Rohan Gupta
# Sneha Joshi
# โ”€โ”€ Append Mode โ€” Adding without losing data โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
f = open("students.txt", "a")     # 'a' = safe append!
f.write("Kavya Reddy\n")          # Added at the END
f.write("Arjun Mehta\n")
f.close()
# Existing names preserved; two new names added at bottom
โš  Common Mistake โ€” Top Exam Trap!

writelines() does NOT add newlines! If you forget \n, all content gets jammed onto one line:

# โŒ WRONG โ€” Everything on one line!
f.writelines(["Math", "Physics", "CS"])
# File: MathPhysicsCS  โ† disaster!

# โœ… CORRECT โ€” Each item on its own line
f.writelines(["Math\n", "Physics\n", "CS\n"])
# File:
# Math
# Physics
# CS
๐Ÿ“‹ Board Exam Tip
Board Exam Hotspot: write() vs writelines() difference table: Feature write() writelines()
Argument Single string List of strings
Returns Integer (char count) None
Newline Must add \n manually Must add \n in each string

๐Ÿ’ง 5.4.3 The flush() Function

Here is something that surprises many beginners:

Python does NOT write to disk immediately! Instead, it uses an invisible I/O Buffer โ€” a small chunk of RAM that collects data before writing it all to disk in one go. This is much faster (fewer disk operations), but there's a risk:

If the program crashes before the buffer is flushed, the data is lost forever! ๐Ÿ’€

flush() forces Python to immediately write all buffered data to the actual disk file โ€” without closing it.

๐Ÿ”‘ Syntax

file_object.flush()

Immediately empties the write buffer to disk. The file stays open for further operations.

import time

# Simulating a log writer / server
f = open("server_log.txt", "w")

f.write("๐ŸŸข Server started at 09:00\n")
f.flush()    # โ† Written to disk RIGHT NOW
# Even if the program crashes after this line,
# this log entry is safely saved!

print("Waiting for requests...")
time.sleep(3)

f.write("๐Ÿ“ฅ Request received from 192.168.1.5\n")
f.flush()    # โ† Saved immediately again!

f.write("โœ… Request processed successfully\n")
# No flush here โ€” this might be lost if crash happens now

f.close()    # close() always flushes automatically
๐Ÿ’ก Study Strategy

Think of flush() like pressing Ctrl+S while writing an important document. Without it, your data lives in the buffer (unsaved). With it, it's safely written to disk. Always use flush() in logging or real-time monitoring programs! ๐Ÿ’พ

๐Ÿง  Memory Trick

flush() = Force Lose the buffer URGENTLY, Save to disk Here! ๐Ÿšฟ Just like flushing a toilet pushes everything out immediately โ€” flush() pushes all buffered data out to the file right now!


๐Ÿงน 5.4.4 Removing Whitespaces After Reading from File

When you read lines from a file, each line carries unwanted baggage โ€” especially the trailing newline character \n. This invisible character causes nasty bugs when you compare strings or display data!

f = open("names.txt", "r")
line = f.readline()
print(line)          # Aman
                     # โ† Extra blank line! Because line = "Aman\n"
                     #   and print() adds another \n
print(repr(line))    # 'Aman\n'  โ† See the hidden \n!
f.close()

Python's three strip methods to the rescue:

  • โœ‚๏ธ strip() โ€” Removes whitespace (\n, spaces, tabs) from BOTH ends

    • Most thorough โ€” cleans both left and right sides
    • Use when you don't care about leading spaces either
  • โœ‚๏ธ lstrip() โ€” Removes whitespace from the LEFT side only

    • Removes leading spaces/tabs/newlines
  • โœ‚๏ธ rstrip() โ€” Removes whitespace from the RIGHT side only

    • Most common for file reading โ€” removes trailing \n
    • Can specify exactly what to remove: rstrip('\n')
line = "   Hello World!   \n"

print(repr(line.strip()))    # 'Hello World!'  โ† both sides cleaned
print(repr(line.lstrip()))   # 'Hello World!   \n'  โ† only left
print(repr(line.rstrip()))   # '   Hello World!'  โ† only right (incl. \n)
print(repr(line.rstrip('\n')))  # '   Hello World!   '  โ† ONLY \n removed
# ๐Ÿงช Real-world example: Read student names cleanly
f = open("students.txt", "r")
students = []
for line in f:
    name = line.strip()     # Remove \n and any extra spaces
    if name:                # Skip blank lines (empty strings are falsy)
        students.append(name)
f.close()
print(students)
# ['Aman Sharma', 'Priya Singh', 'Rohan Gupta', 'Sneha Joshi'] โœ…
โš  Common Mistake โ€” Sneaky Bug in Comparisons!

f = open("data.txt", "r")
for line in f:
    # line = "Python\n" from file

    if line == "Python":      # โŒ ALWAYS FALSE! \n is hiding!
        print("Found!")

    if line.strip() == "Python":   # โœ… CORRECT!
        print("Found!")
f.close()

This is one of the most common bugs in student programs. Always strip before comparing!

๐Ÿ’ก Study Strategy

Make stripping a habit. Whenever you read from a file, immediately chain .strip():

data = f.readline().strip()      # Read AND strip in one line!
lines = [l.strip() for l in f]   # List comprehension magic!

๐Ÿ—บ๏ธ 5.4.5 Significance of File Pointer in File Handling

Imagine you're reading a thick novel ๐Ÿ“š. You place a bookmark to remember where you stopped. When you come back, you don't re-read from page 1 โ€” you jump to the bookmark!

Python's file pointer (also called file position indicator) is exactly like that bookmark:

  • It's a number representing the current position in the file (measured in bytes from the start)
  • It moves automatically as you read or write
  • It can be queried with tell()
  • It can be moved with seek()

๐Ÿ“ The tell() Function โ€” "Where am I?"

๐Ÿ”‘ Syntax

position = file_object.tell()

Returns the current byte position of the file pointer as an integer.

# File "hello.txt" contains: "Hello World"
#  Positions:                  0123456789A
#  (A = 10)

f = open("hello.txt", "r")
print(f.tell())      # 0  โ†’ At the very beginning

f.read(5)            # Read "Hello" โ†’ pointer advances 5 bytes
print(f.tell())      # 5  โ†’ Now pointing at the space before "World"

f.read(1)            # Read " " (space)
print(f.tell())      # 6  โ†’ Now pointing at 'W'

f.read()             # Read "World" (remaining)
print(f.tell())      # 11 โ†’ End of file

f.close()

๐Ÿงญ The seek() Function โ€” "Take me there!"

๐Ÿ”‘ Syntax

file_object.seek(offset, from_where)
  • offset โ†’ Number of bytes to move (can be 0 or positive)
  • from_where โ†’ The starting reference point:
    • 0 โ†’ From the beginning of the file (default)
    • 1 โ†’ From the current position
    • 2 โ†’ From the end of the file
  • In text mode, only seek(0) and seek(n, 0) (from beginning) are reliably supported
# File "hello.txt" contains: "Hello World"

f = open("hello.txt", "r")

# Jump to position 6 from beginning
f.seek(6)
print(f.read())       # "World"

# Go back to the very start
f.seek(0)
print(f.read(5))      # "Hello"

# Jump to position 0 again and check
f.seek(0)
print(f.tell())       # 0 โ†’ Back to start โœ…

f.close()
# Practical Example: Re-reading a file
f = open("scores.txt", "r")

# First pass: Find the highest score
lines = f.readlines()
scores = [int(line.strip()) for line in lines]
print("Max Score:", max(scores))

# Go back to beginning for a second pass!
f.seek(0)

# Second pass: Print all scores
for line in f:
    print("Score:", line.strip())

f.close()
๐Ÿง  Memory Trick

  • tell() = "Tell me where you are right now!" ๐Ÿ—ฃ๏ธ
  • seek() = "Seek (go to) this position!" ๐Ÿ” Together they're like GPS for your file โ€” you can always know your position and jump anywhere! ๐Ÿ—บ๏ธ
๐Ÿ“‹ Board Exam Hotspot

For text files in Python:

  • seek(0) โ†’ Go to beginning โœ… (fully supported)
  • seek(n, 0) โ†’ Go to byte n from start โœ… (supported)
  • seek(n, 1) or seek(n, 2) โ†’ Not reliably supported in text mode โš ๏ธ

For full random access using seek(n, 1) and seek(n, 2), you need binary mode ('rb').


๐Ÿงญ File Pointer Flow โ€” Visual Guide

flowchart LR
    START["๐Ÿ“ Position: 0\nStart of File"]
    AFTER_READ5["๐Ÿ“ Position: 5\nAfter read(5)"]
    AFTER_LINE["๐Ÿ“ Next line\nAfter readline()"]
    BACK_START["๐Ÿ“ Position: 0\nAfter seek(0)"]
    EOF["๐Ÿ“ End of File\ntell() = file size"]

    START -->|"f.read(5)\nreads 5 chars"| AFTER_READ5
    AFTER_READ5 -->|"f.readline()\nreads rest of line"| AFTER_LINE
    AFTER_LINE -->|"f.seek(0)\njump back!"| BACK_START
    BACK_START -->|"Same as START"| START
    AFTER_LINE -->|"f.read()\nreads everything left"| EOF

    classDef normalNode fill:none;
    classDef elseNode fill:none;
    classDef tryNode fill:none;

    class START normalNode;
    class AFTER_READ5 elseNode;
    class AFTER_LINE elseNode;
    class BACK_START tryNode;
    class EOF normalNode;

๐ŸŽฏ Complete Text File Program โ€” All Concepts Together!

# ๐Ÿซ Student Marks Manager โ€” Complete File Handling Demo
# Covers: write, writelines, flush, read, readline, readlines,
#         strip, seek, tell

FILENAME = "marks.txt"

# โ”€โ”€ STEP 1: Create the file and write data โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
print("=== Step 1: Writing Data ===")
f = open(FILENAME, "w")
f.write("Aman Sharma - 95\n")
f.write("Priya Singh - 88\n")
f.writelines(["Rohan Gupta - 76\n", "Sneha Joshi - 92\n"])
f.flush()    # Force save to disk immediately!
print(f"Data written! Pointer at position: {f.tell()}")
f.close()

# โ”€โ”€ STEP 2: Read entire file โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
print("\n=== Step 2: Full File Content ===")
f = open(FILENAME, "r")
content = f.read()
print(content)
f.close()

# โ”€โ”€ STEP 3: Read line by line with strip โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
print("\n=== Step 3: Cleaned Lines ===")
f = open(FILENAME, "r")
for line in f:
    clean = line.strip()       # Remove \n
    print(f"  > {clean}")
f.close()

# โ”€โ”€ STEP 4: seek() and tell() demo โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
print("\n=== Step 4: Pointer Navigation ===")
f = open(FILENAME, "r")
print(f"Start position: {f.tell()}")     # 0
first_line = f.readline().strip()
print(f"After readline: position = {f.tell()}")
print(f"First student: {first_line}")

f.seek(0)    # Go back to beginning!
print(f"After seek(0): position = {f.tell()}")  # 0 again

all_lines = f.readlines()
print(f"Total students: {len(all_lines)}")
print(f"Third student: {all_lines[2].strip()}")
f.close()

# โ”€โ”€ STEP 5: Append new record โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
print("\n=== Step 5: Adding New Student ===")
f = open(FILENAME, "a")         # Safe append!
f.write("Kavya Reddy - 98\n")
f.close()
print("New student added! โœ…")

๐Ÿ“ก 5.5 Standard Input, Output and Error Streams

Every Python program has three data channels automatically available โ€” even before you open a single file. These are called Standard Streams, and they're accessible through the sys module.

  • ๐ŸŽค sys.stdin โ€” Standard Input Stream

    • By default, reads from the keyboard
    • The input() function is just a convenient wrapper around sys.stdin
    • Can be redirected to read from a file instead of keyboard!
  • ๐Ÿ–ฅ๏ธ sys.stdout โ€” Standard Output Stream

    • By default, writes to the console/screen
    • The print() function internally uses sys.stdout
    • Can be redirected to write to a file instead of screen!
  • ๐Ÿšจ sys.stderr โ€” Standard Error Stream

    • By default, writes error/warning messages to the screen
    • Separate from stdout โ€” even if stdout is redirected, errors still appear on screen
    • Python's own error messages (tracebacks) go to stderr
import sys

# Direct usage of standard streams
sys.stdout.write("Hello from stdout!\n")     # Same as print()
sys.stderr.write("โš ๏ธ Warning: Low memory!\n")  # Error channel

# Reading from stdin (same as input())
sys.stdout.write("Enter your name: ")
name = sys.stdin.readline().strip()
print(f"Hello, {name}!")
import sys

# ๐ŸŒŸ Stream Redirection โ€” Powerful Technique!
print("This goes to SCREEN (normal)")

# Redirect stdout to a file
original_stdout = sys.stdout      # Save the original
log_file = open("output_log.txt", "w")
sys.stdout = log_file             # All print() now goes to file!

print("This line goes to the FILE, not screen! ๐Ÿ“")
print("Magic of stream redirection! ๐ŸŽฉ")

sys.stdout = original_stdout      # Restore normal output
log_file.close()

print("We're back on SCREEN! โœ…")
๐Ÿ“‹ Board Exam Hotspot

The three standard streams are:

  • sys.stdin โ†’ Standard input (keyboard by default)
  • sys.stdout โ†’ Standard output (screen by default)
  • sys.stderr โ†’ Standard error (screen by default โ€” separate from stdout!)

All three can be redirected to files for powerful I/O control!

๐Ÿง  Memory Trick

Think of the three streams like a classroom lecture:

  • sys.stdin = Students asking questions ๐Ÿ™‹ (input coming IN)
  • sys.stdout = Teacher writing on the board ๐Ÿ“ (output going OUT)
  • sys.stderr = Principal's urgent announcement ๐Ÿ“ข (critical alerts that bypass normal flow!)

๐Ÿ† Chapter Revision

๐Ÿ“‹ Board Exam Hotspot โ€” Complete Quick Reference

Function Purpose Returns
open(file, mode) Open a file File object
close() Close and save the file None
read() Read entire file as string String
read(n) Read next n characters String
readline() Read one line (with \n) String
readlines() Read all lines List of strings
write(s) Write string s to file Int (char count)
writelines(L) Write list L of strings None
flush() Force buffer to disk immediately None
tell() Get current pointer position Integer (bytes)
seek(n) Move pointer to byte n None
strip() Remove whitespace both ends String
rstrip() Remove right-side whitespace String
lstrip() Remove left-side whitespace String
๐Ÿ’ก Study Strategy โ€” 6 Most Common CBSE Questions

  1. ๐Ÿ–Š๏ธ "Difference between read(), readline(), readlines()"
  2. ๐Ÿ–Š๏ธ "Difference between 'w' and 'a' file opening mode"
  3. ๐Ÿ–Š๏ธ "Write a program to count lines / words / characters in a file"
  4. ๐Ÿ–Š๏ธ "Write a program to copy content of one file to another"
  5. ๐Ÿ–Š๏ธ "Explain seek() and tell() with an example"
  6. ๐Ÿ–Š๏ธ "What is flush()? When and why is it used?"

๐Ÿงฉ CBSE Practice Programs

# โœ๏ธ Program 1: Count Lines, Words & Characters in a File
f = open("essay.txt", "r")
lines = words = chars = 0
for line in f:
    lines += 1
    words += len(line.split())
    chars += len(line)
f.close()
print(f"Lines : {lines}")
print(f"Words : {words}")
print(f"Chars : {chars}")
# โœ๏ธ Program 2: Copy One File to Another
src = open("source.txt", "r")
dst = open("destination.txt", "w")
for line in src:
    dst.write(line)
src.close()
dst.close()
print("File copied successfully! โœ…")
# โœ๏ธ Program 3: Search for a Keyword in a File
def search_keyword(filename, keyword):
    try:
        f = open(filename, "r")
        count = 0
        line_no = 0
        for line in f:
            line_no += 1
            if keyword.lower() in line.lower():
                print(f"Line {line_no}: {line.rstrip()}")
                count += 1
        f.close()
        print(f"\n'{keyword}' found in {count} line(s).")
    except FileNotFoundError:
        print(f"Error: '{filename}' not found!")

search_keyword("notes.txt", "Python")
# โœ๏ธ Program 4: Display Lines Starting with a Vowel (CBSE Favourite!)
f = open("words.txt", "r")
vowels = "AEIOUaeiou"
for line in f:
    line = line.strip()
    if line and line[0] in vowels:     # Check first character
        print(line)
f.close()
# โœ๏ธ Program 5: Using seek() to Read File Twice
f = open("data.txt", "r")

# First read
print("=== First Read ===")
print(f.read())

# Use seek(0) to go back to beginning!
f.seek(0)

# Second read
print("=== Second Read (after seek) ===")
for line in f:
    print(line.rstrip())

f.close()
โš  Common Mistake โ€” Top 5 File Handling Traps in Exams

  1. โŒ Forgetting f.close() โ€” always close your files!
  2. โŒ Using 'w' instead of 'a' โ€” accidentally erasing all existing data
  3. โŒ Not adding \n in write() or writelines() โ€” everything on one line
  4. โŒ Not using .strip() when comparing file content to strings
  5. โŒ Opening a non-existent file in 'r' mode without a try-except block
Take the Chapter 05A Quiz Custom Quiz
Solved Board Questions

Practice real board exam questions for this chapter.

View Solved Board Questions
Learning Support

Need Help With This Chapter?

Save key topics for exam revision, ask questions to teachers, or submit content corrections.

Verified Doubts & Teacher Answers

Chapter 05A Quiz