Unit 4 · Modules and File Handling
Reading and Writing Files
Master the techniques of reading from and writing to files in Python with practical programs for copying, counting, and processing text data.
Introduction
After learning how to open and close files, the next step is to actually read data from files and write data to them. This chapter covers practical file operations with multiple real-world programs commonly asked in university exams.
We will cover read(), readline(), readlines() for reading, and write(), writelines() for writing, along with practical programs that combine reading and writing.
University Definition
Reading a file means extracting data from a file on disk into program variables. Writing a file means storing program data into a file on disk. The write() method writes a string to a file and returns the number of characters written. The writelines() method writes a list of strings to a file.
Table of Contents
Reading Methods in Detail
# Assume "sample.txt" contains:
# Line 1: Hello World
# Line 2: Python is great
# Line 3: File handling is important
# ---- read() ----
with open("sample.txt", "r") as f:
data = f.read() # Reads entire file as one string
print(data)
print(type(data)) # <class 'str'>
# ---- read(n) ----
with open("sample.txt", "r") as f:
chunk = f.read(11) # Read first 11 characters
print(chunk) # "Line 1: He"
# ---- readline() ----
with open("sample.txt", "r") as f:
line1 = f.readline() # "Line 1: Hello World\n"
line2 = f.readline() # "Line 2: Python is great\n"
print(line1.strip()) # "Line 1: Hello World"
print(line2.strip()) # "Line 2: Python is great"
# ---- readlines() ----
with open("sample.txt", "r") as f:
all_lines = f.readlines()
print(all_lines)
# ['Line 1: Hello World\n', 'Line 2: Python is great\n', 'Line 3: ...']
print(len(all_lines)) # 3
Reading with Loop (Memory Efficient)
# Most memory-efficient: iterate line by line
with open("large_file.txt", "r") as f:
for line in f:
print(line.strip())
Writing Methods
write() Method
# write() writes a string and returns character count
with open("output.txt", "w") as f:
count = f.write("Hello, World!\n")
print(f"Characters written: {count}") # 14
f.write("Python\n")
f.write("File Handling\n")
writelines() Method
# writelines() writes a list of strings (no newlines added automatically)
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
# Note: writelines() does NOT add \n automatically
# You must include \n in each string
Appending to a File
# Append mode preserves existing content
with open("log.txt", "a") as f:
f.write("New log entry added.\n")
f.write("Another entry.\n")
University Exam Tip
write() returns the number of characters written. writelines() does not add newlines automatically — you must include \n in each string. Neither write() nor writelines() adds newlines automatically.
Program: Copy a File
Method 1: Character by Character
def copy_file(source, destination):
with open(source, "r") as fin, open(destination, "w") as fout:
char = fin.read(1)
while char:
fout.write(char)
char = fin.read(1)
print(f"File copied: {source} -> {destination}")
copy_file("input.txt", "output.txt")
Method 2: Line by Line
def copy_file_lines(source, destination):
with open(source, "r") as fin, open(destination, "w") as fout:
for line in fin:
fout.write(line)
print(f"File copied successfully!")
copy_file_lines("input.txt", "output.txt")
Method 3: Read Entire File
def copy_file_full(source, destination):
with open(source, "r") as fin:
content = fin.read()
with open(destination, "w") as fout:
fout.write(content)
print("Copy complete!")
copy_file_full("input.txt", "output.txt")
Program: Count Lines, Words, and Characters
def count_file_stats(filename):
"""Count lines, words, and characters in a file."""
lines = 0
words = 0
chars = 0
with open(filename, "r") as f:
for line in f:
lines += 1
words += len(line.split())
chars += len(line)
return lines, words, chars
# Usage
filename = "data.txt"
lines, words, chars = count_file_stats(filename)
print(f"Lines: {lines}")
print(f"Words: {words}")
print(f"Characters: {chars}")
# Alternative: simpler one-liner approach
with open("data.txt", "r") as f:
content = f.read()
print(f"Lines: {content.count(chr(10)) + 1}")
print(f"Words: {len(content.split())}")
print(f"Characters: {len(content)}")
More Practical Programs
Program: Count Specific Word in File
def count_word(filename, target):
"""Count occurrences of a word in a file."""
count = 0
with open(filename, "r") as f:
for line in f:
words = line.split()
for word in words:
if word.lower() == target.lower():
count += 1
return count
print(count_word("data.txt", "python")) # e.g., 5
Program: Read and Display File in Reverse
def reverse_file(filename):
"""Display file content in reverse order."""
with open(filename, "r") as f:
lines = f.readlines()
for line in reversed(lines):
print(line.strip())
reverse_file("data.txt")
Program: Search and Replace in File
def search_replace(source, dest, old_text, new_text):
"""Replace all occurrences of old_text with new_text."""
with open(source, "r") as fin:
content = fin.read()
content = content.replace(old_text, new_text)
with open(dest, "w") as fout:
fout.write(content)
print("Replacement complete!")
search_replace("input.txt", "output.txt", "Python", "Java")
Program: Merge Two Files
def merge_files(file1, file2, output):
"""Merge two files into a third file."""
with open(file1, "r") as f1, open(file2, "r") as f2:
content1 = f1.read()
content2 = f2.read()
with open(output, "w") as out:
out.write(content1)
out.write("\n")
out.write(content2)
print("Files merged successfully!")
merge_files("file1.txt", "file2.txt", "merged.txt")
Program: Read CSV Data from File
# File "students.csv" contains:
# Name,Grade,Score
# Alice,A,95
# Bob,B,82
with open("students.csv", "r") as f:
header = f.readline().strip().split(",")
print("Columns:", header)
for line in f:
data = line.strip().split(",")
print(f"Name: {data[0]}, Grade: {data[1]}, Score: {data[2]}")
# Output:
# Columns: ['Name', 'Grade', 'Score']
# Name: Alice, Grade: A, Score: 95
# Name: Bob, Grade: B, Score: 82
Program: Write Student Records to File
def write_student_records(filename, students):
"""Write student records to a file."""
with open(filename, "w") as f:
f.write("Name,Roll,Score\n")
for name, roll, score in students:
f.write(f"{name},{roll},{score}\n")
print("Records saved!")
students = [
("Alice", 101, 95),
("Bob", 102, 82),
("Charlie", 103, 91)
]
write_student_records("students.txt", students)
# Read them back
with open("students.txt", "r") as f:
for line in f:
print(line.strip())
Key Points
read() reads the entire file; readline() reads one line; readlines() returns a list of lines.
write() writes a string and returns the count of characters written.
writelines() writes a list of strings but does NOT add newlines.
Always use with statement for safe file handling.
"a" mode appends without erasing; "w" mode erases existing content.
Iterating over a file object is the most memory-efficient way to read large files.
Use strip() to remove trailing \n when processing lines.
For copying files, line-by-line processing is the most practical approach.
Practice Questions
Q1: Write a program to copy content from one file to another.
Answer: Open source with "r" and destination with "w". Read from source and write to destination using a loop.
Q2: What is the difference between write() and writelines()?
Answer: write() writes a single string. writelines() writes a list of strings. Neither adds newlines automatically.
Q3: Write a program to count the number of vowels in a text file.
Answer: Read the file, iterate over each character, and count if it's in "aeiouAEIOU".
Q4: Write a program to find and display the longest word in a text file.
Answer: Read all words, track the longest using len(), and print the result.
Q5: Write a program to read a file and write only the uppercase lines to another file.
Answer: Read line by line, check line.isupper(), and write matching lines to the destination file.
Summary
read(), readline(), readlines() are used for reading file content.
write() and writelines() are used for writing content to files.
Always use the with statement for automatic file closing.
Common programs: copy file, count lines/words, search/replace, merge files.
Use "a" mode to append and "w" mode to overwrite.
For large files, process line-by-line to save memory.