File Handling
File Handling
2. Exam-Style Questions
Helps you get familiar with the type and format of questions
asked in the exam.
Helps you understand both the syntax and the concepts behind
the code.
8. Build Confidence
9. Time Management
The solutions are structured in a way that helps you learn how
to approach questions within a time limit.
Question 2
Write a Python function named replaceAndSave() that reads a
text file named INPUT.TXT, replaces all occurrences of the
word "cloud" with "sky", and saves the modified content to a new
file named OUTPUT.TXT.
For example, if the content of INPUT.TXT is:
The cloud is white and fluffy.
Cloud computing is an evolving technology.
The blue sky stretches over the horizon.
The content of OUTPUT.TXT after execution should be:
The sky is white and fluffy.
Sky computing is an evolving technology.
The blue sky stretches over the horizon.
Question 3
Define a Python function findLongestLine() that reads a file
named LINES.TXT and displays the longest line (in terms of the
number of characters) present in the file.
For example, if the content of LINES.TXT is:
Short lines are easy to read.
But some lines can be unexpectedly long and descriptive, like this
one!
Tiny.
Question 4
Write a Python function named reverseContent() that reads a
text file DATA.TXT and creates a new file REVERSE.TXT,
where each line of DATA.TXT is written in reverse order. For
example, if DATA.TXT contains:
Hello, world!
Python is fun.
Keep coding.
Question 5
Define a function filterShortLines() that reads a text file named
PARAGRAPH.TXT and creates a new file SHORTLINES.TXT
that contains only those lines from PARAGRAPH.TXT which have
fewer than 50 characters. For example, if PARAGRAPH.TXT
contains:
This is a short line.
This line, however, is a bit too long and detailed to be considered
short.
Python makes file handling simple.
Short and sweet!
Question 6
Write a Python function named wordFrequency() that reads a file
named ARTICLE.TXT and displays the frequency of each word in
the file in alphabetical order.
For example, if the content of ARTICLE.TXT is:
Python is easy to learn. Python is powerful.
Learn Python for data science.
The function should display:
Frequency of words:
Python: 3
data: 1
easy: 1
for: 1
is: 2
learn: 1
powerful: 1
science: 1
to: 1
Question 7
Create a function named addLineNumbers() that reads a file
named CONTENT.TXT and writes its content to a new file
NUMBERED.TXT. Each line in NUMBERED.TXT should begin with
its corresponding line number.
For example, if CONTENT.TXT contains:
Python is amazing.
I love coding.
File handling is fun!
Then NUMBERED.TXT should contain:
1. Python is amazing.
2. I love coding.
3. File handling is fun!
Question 8
Define a Python function findPalindromes() that reads a text file
WORDS.TXT and displays all the words that are palindromes.
Assume that each word is separated by a space or a newline.
For example, if WORDS.TXT contains:
level radar python madam racecar coding
The function should display:
Palindromes found: level, radar, madam, racecar
Question 9
Write a Python function compareFiles() that takes the names of
two text files FILE1.TXT and FILE2.TXT as input and checks
whether their contents are identical.
For example, if the contents of FILE1.TXT and FILE2.TXT are:
FILE1.TXT:
Python programming is fun.
File handling is important.
FILE2.TXT:
Python programming is fun.
File handling is important.
The function should return:
The files are identical.
Question 10
Create a Python function named extractEmails() that reads a file
CONTACTS.TXT and extracts all email addresses present in the
file.
For example, if CONTACTS.TXT contains:
John: [email protected]
Jane: [email protected]
Admin: [email protected]
Contact us for queries!
The function should display:
Extracted emails:
[email protected]
[email protected]
[email protected]
SOLUTIONS OF TOP 10
Solution 1:
def countWordLines():
try:
with open("WORDS.TXT", "r") as file:
lines = file.readlines()
count = 0
for line in lines:
if "Python" in line:
count += 1
print(f"Number of lines containing the
word 'Python': {count}")
except FileNotFoundError:
print("File WORDS.TXT not found.")
word.
2. Important Python Functions and Concepts:
o File Handling:
Always use with open() to automatically close the
o Loops:
for line in lines: Loops through each line in the file.
Solution 2:
def replaceAndSave():
try:
with open("INPUT.TXT", "r") as infile:
content = infile.read()
modified_content = content.replace("cloud",
"sky")
with open("OUTPUT.TXT", "w") as outfile:
outfile.write(modified_content)
print("File saved as OUTPUT.TXT with
replacements.")
except FileNotFoundError:
print("File INPUT.TXT not found.")
Solution 3:
def findLongestLine():
try:
with open("LINES.TXT", "r") as file:
lines = file.readlines()
longest_line = max(lines, key=len)
print(f"Longest line:
{longest_line.strip()}")
except FileNotFoundError:
print("File LINES.TXT not found.")
Solution 4:
def reverseContent():
try:
with open("DATA.TXT", "r") as infile:
lines = infile.readlines()
with open("REVERSE.TXT", "w") as outfile:
for line in lines:
outfile.write(line[::-1] + "\n")
print("Content reversed and saved in
REVERSE.TXT.")
except FileNotFoundError:
print("File DATA.TXT not found.")
Solution 5:
def filterShortLines():
try:
with open("PARAGRAPH.TXT", "r") as infile:
lines = infile.readlines()
with open("SHORTLINES.TXT", "w") as outfile:
for line in lines:
if len(line.strip()) < 50:
outfile.write(line)
print("Short lines saved in SHORTLINES.TXT.")
except FileNotFoundError:
print("File PARAGRAPH.TXT not found.")
Solution 6:
def wordFrequency():
try:
with open("ARTICLE.TXT", "r") as file:
content = file.read().lower()
words = content.split()
frequency = {}
for word in words:
word = word.strip(".,!?")
frequency[word] = frequency.get(word,
0) + 1
for word in sorted(frequency):
print(f"{word}: {frequency[word]}")
except FileNotFoundError:
print("File ARTICLE.TXT not found.")
Solution 7:
def addLineNumbers():
try:
with open("CONTENT.TXT", "r") as infile:
lines = infile.readlines()
with open("NUMBERED.TXT", "w") as outfile:
for i, line in enumerate(lines, start=1):
outfile.write(f"{i}. {line}")
print("Content saved in NUMBERED.TXT with
line numbers.")
except FileNotFoundError:
print("File CONTENT.TXT not found.")
NUMBERED.TXT.
2. Important Python Functions and Concepts:
o Enumerate:
enumerate(iterable, start=n): Generates pairs of
Solution: 8
def findPalindromes():
try:
with open ("WORDS.TXT", "r") as file:
words = file.read().split()
palindromes = [word for word in words if
word == word[::-1]]
print(f"Palindromes found: {',
'.join(palindromes)}")
except FileNotFoundError:
print("File WORDS.TXT not found.")
Solution 9:
def compareFiles():
try:
with open("FILE1.TXT", "r") as file1,
open("FILE2.TXT", "r") as file2:
content1 = file1.read()
content2 = file2.read()
if content1 == content2:
print("The files are identical.")
else:
print("The files are not identical.")
except FileNotFoundError:
print("One or both files not found.")
Quick Notes for Students
1. Step-by-Step Explanation:
o Open Both Files Simultaneously:
Solution 10:
import re
def extractEmails():
try:
with open("CONTACTS.TXT", "r") as file:
content = file.read()
emails = re.findall(r"[a-zA-Z0-9._%+-
]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", content)
if emails:
print("Extracted emails:")
for email in emails:
print(email)
else:
print("No emails found in the file.")
except FileNotFoundError:
print("File CONTACTS.TXT not found.")
re.findall(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-
Z]{2,}", content): Uses a regular expression to find all
valid email addresses in the file content.
o Regular Expressions:
[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}:
Matches typical email address formats.
o Context Manager:
o Exception Handling: