## ๐๏ธ 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! ๐พ
---
::: grid
::: card 5.1 | Introduction | Why programs need files โ temporary RAM vs permanent disk storage | Persistence, Storage
::: card 5.2 | Data Files | Text files vs Binary files โ what's the difference? | Text, Binary, ASCII
::: card 5.3 | Open & Close | The open() and close() functions โ the lifecycle of a file | open(), close(), modes
::: card 5.4 | Text File Operations | read, readline, readlines, write, writelines, flush, seek, tell | All text file methods
::: card 5.5 | Standard Streams | stdin, stdout, stderr โ the three invisible data channels | sys module, redirection
:::
---
## ๐ 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.
> [!NOTE]
> **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
> [!IMPORTANT]
> **Board Exam Hotspot:** CBSE loves asking โ *"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.
> [!RULE]
> **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+")`
> [!WARNING]
> **Common Mistake:** The difference between `'w'` and `'a'` trips up almost every student! 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. ๐จ
> [!TIP]
> **Study Strategy:** Use this rhyme to remember:
> - **`r`** = **R**ead what's there (file must exist!)
> - **`w`** = **W**ipe clean, then Write (dangerous โ erases!)
> - **`a`** = **A**dd to the end (always safe!)
---
### ๐บ๏ธ The File Lifecycle โ Open โ Use โ Close
```mermaid
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
> [!RULE]
> **Syntax:**
> ```
> file_object.close()
> ```
```python
# Standard open โ use โ close pattern
f = open("story.txt", "r")
content = f.read()
print(content)
f.close() # ๐ Always close!
```
```python
# ๐ 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
```
> [!IMPORTANT]
> **Board Exam Hotspot:** The `with` statement is increasingly appearing in CBSE sample papers. It's the **preferred, professional 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 has its own superpower!
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
```python
# โโ 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!
```
```python
# โโ 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()
```
```python
# โโ 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()
```
```python
# โโ 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()
```
```python
# โโ ๐ 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()
```
> [!IMPORTANT]
> **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 |
> [!WARNING]
> **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**
```python
# โโ 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
```
```python
# โโ 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
```
```python
# โโ 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
```
> [!WARNING]
> **Common Mistake โ Top Exam Trap!** `writelines()` does NOT add newlines! If you forget `\n`, all content gets jammed onto one line:
> ```python
> # โ 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
> ```
> [!IMPORTANT]
> **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's a secret Python doesn't tell 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**.
> [!RULE]
> **Syntax:**
> ```
> file_object.flush()
> ```
> Immediately empties the write buffer to disk. The file stays open for further operations.
```python
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
```
> [!TIP]
> **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! ๐พ
> [!NOTE]
> **Memory Trick:** **`flush()`** = **F**orce **L**ose the buffer **U**RGENTLY, **S**ave to disk **H**ere! ๐ฟ
> 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!
```python
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')`
```python
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
```
```python
# ๐งช 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'] โ
```
> [!WARNING]
> **Common Mistake โ Sneaky Bug in Comparisons!**
> ```python
> 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!
> [!TIP]
> **Study Strategy:** Make stripping a **habit**. Whenever you read from a file, immediately chain `.strip()`:
> ```python
> 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?"
> [!RULE]
> **Syntax:**
> ```
> position = file_object.tell()
> ```
> Returns the **current byte position** of the file pointer as an integer.
```python
# 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!"
> [!RULE]
> **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
```python
# 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()
```
```python
# 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()
```
> [!NOTE]
> **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! ๐บ๏ธ
> [!IMPORTANT]
> **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
```mermaid
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!
```python
# ๐ซ 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`
```python
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}!")
```
```python
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! โ
")
```
> [!IMPORTANT]
> **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!
> [!NOTE]
> **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 Ready!
> [!IMPORTANT]
> **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 |
> [!TIP]
> **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
```python
# โ๏ธ 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}")
```
```python
# โ๏ธ 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! โ
")
```
```python
# โ๏ธ 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")
```
```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()
```
```python
# โ๏ธ 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()
```
> [!WARNING]
> **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
Back to List
Calculating...
UNIT 1 : CH 5
Dec 09, 2025
๐๏ธ File Handling in Python (Text File)
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
Loading resolved questions for this note...