๐๏ธ 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!
Introduction
Why programs need files โ temporary RAM vs permanent disk storage
PersistenceStorageData Files
Text files vs Binary files โ what's the difference?
TextBinaryASCIIOpen & Close
The open() and close() functions โ the lifecycle of a file
open()close()modesText File Operations
read, readline, readlines, write, writelines, flush, seek, tell
All text file methodsStandard 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.
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
.pyfile 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
.jpgphoto, an.mp3song, a compiled.exeprogram
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
\nas 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.
file_object = open(filename, mode)
filenameโ Name (or full path) of the file as a stringmodeโ 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
FileNotFoundErrorif 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
FileNotFoundErrorif 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+")
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. ๐จ
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
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
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 stringf.read(n)โ Reads exactlyncharacters 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
\nat the end - Returns an empty string
""when end of file is reached (notNone!) - Memory efficient โ great for processing huge files line by line
- Each call automatically advances the pointer to the next line
- Reads and returns one line, including its
-
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
\ncharacter - 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 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 |
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
\nyourself! - 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
\nin 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
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 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.
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
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! ๐พ
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')
- Most common for file reading โ removes trailing
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'] โ
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!
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?"
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!"
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 position2โ From the end of the file
- In text mode, only
seek(0)andseek(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()
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! ๐บ๏ธ
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)orseek(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 aroundsys.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 usessys.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! โ
")
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!
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!)
Text file vs Binary file
- Text file โ stores characters, human-readable, each line ends with
\n(.txt,.py,.csv) - Binary file โ stores raw bytes exactly as in memory, not human-readable, no lines (
.dat,.jpg,.exe)
Opening and Closing
f = open("notes.txt", "r")โ returns a file object (file handle); the default mode is"r"f.close()โ saves buffered data to disk and frees the filewith open("notes.txt") as f:โ closes the file automatically, even if an error happens (best practice)
| Mode | Does | File missing | Existing data | Pointer starts at |
|---|---|---|---|---|
"r" |
read only | FileNotFoundError |
kept | beginning |
"w" |
write only | creates it | erased | beginning |
"a" |
write at the end | creates it | kept | end |
"r+" |
read + write | FileNotFoundError |
kept | beginning |
"w+" |
write + read | creates it | erased | beginning |
"a+" |
append + read | creates it | kept | end |
Add b for a binary file: "rb", "wb", "ab", "rb+" โฆ
Reading (each read moves the file pointer forward)
| Method | Returns | Reads |
|---|---|---|
read() |
one string | the whole file |
read(n) |
one string | the next n characters |
readline() |
one string (with its \n) |
one line |
readlines() |
a list of strings | all lines |
- At the end of the file,
read()andreadline()return""(an empty string, notNone) for line in f:โ reads one line at a time (easiest way to process a big file)- Lines keep their
\nโ useline.strip()/rstrip("\n"), orprint(line, end="")to avoid double spacing
Writing
write(s)โ writes one string, returns the number of characters written; adds no\nby itselfwritelines(lst)โ writes every string in a list, returnsNone; also adds no\nflush()โ forces the buffer onto the disk now, without closing the file
File pointer
f.tell()โ current position (bytes from the start)f.seek(offset, from_where)โ0= from the beginning (default),1= from the current position,2= from the end- In text mode, move from the beginning (
seek(0),seek(n)); a non-zeroseek(n, 1)orseek(n, 2)gives an error there and needs binary mode
Standard streams (import sys)
sys.stdinโ keyboard input |sys.stdoutโ screen output |sys.stderrโ error messages (a separate channel)
Quick check: predict the output (poem.txt holds two lines: Roses are red, and Violets are blue,)
f = open("poem.txt", "r")
print(f.read(5))
print(f.tell())
print(f.readline(), end="")
print(len(f.readlines()))
f.close()
Output:
Roses
5
are red,
1
read(5) takes "Roses" and leaves the pointer at 5. readline() reads the rest of that line (" are red," plus its \n), so readlines() gets only the one remaining line.
๐ Chapter Revision
| 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 |
- ๐๏ธ "Difference between
read(),readline(),readlines()" - ๐๏ธ "Difference between
'w'and'a'file opening mode" - ๐๏ธ "Write a program to count lines / words / characters in a file"
- ๐๏ธ "Write a program to copy content of one file to another"
- ๐๏ธ "Explain
seek()andtell()with an example" - ๐๏ธ "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()
- โ Forgetting
f.close()โ always close your files! - โ Using
'w'instead of'a'โ accidentally erasing all existing data - โ Not adding
\ninwrite()orwritelines()โ everything on one line - โ Not using
.strip()when comparing file content to strings - โ Opening a non-existent file in
'r'mode without a try-except block