0% found this document useful (0 votes)
80 views23 pages

File Handling

This document provides a TOP 10 collection of questions and solutions aimed at helping Class 12 Computer Science students prepare for their exams. It covers essential programming concepts, exam-style questions, and detailed solutions with step-by-step explanations, focusing on best coding practices and problem-solving skills. The document also emphasizes the importance of error handling, file management, and time management to boost students' confidence and exam readiness.

Uploaded by

a03496819
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views23 pages

File Handling

This document provides a TOP 10 collection of questions and solutions aimed at helping Class 12 Computer Science students prepare for their exams. It covers essential programming concepts, exam-style questions, and detailed solutions with step-by-step explanations, focusing on best coding practices and problem-solving skills. The document also emphasizes the importance of error handling, file management, and time management to boost students' confidence and exam readiness.

Uploaded by

a03496819
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

WHY TOP 10?

This TOP 10 collection of questions and solutions is crafted to help


Class 12 Computer Science students prepare effectively and
efficiently for their exams. HereÕs how this PDF will support your
preparation:

1. Focus on Key Topics

 Covers essential programming concepts such as file handling,


string operations, error handling, and regular expressions.

 Helps you master topics that are frequently tested in exams.

2. Exam-Style Questions

 The questions are modelled after the actual exam pattern,


ensuring you're prepared for similar questions.

 Helps you get familiar with the type and format of questions
asked in the exam.

3. Clear, Step-by-Step Explanations

 Each solution provides a detailed breakdown of the code and


its logic.

 Helps you understand both the syntax and the concepts behind
the code.

4. Strengthen Problem-Solving Skills

 Encourages critical thinking and problem-solving by guiding you


through each solution.

 Helps you break down complex problems into manageable steps.

5. Learn Best Coding Practices

 Solutions follow best practices, such as clean code, proper


indentation, and meaningful variable names.
 Helps you write neat, efficient, and readable code.

6. Focus on Error Handling

 Emphasizes the importance of error handling and considering


edge cases.

 Prepares you to write robust and error-free code.

7. Practical File Handling

 Uses real-world examples like reading and modifying files (e.g.,


WORDS.TXT, INPUT.TXT).

 Teaches you how to work with files, which is an essential skill in


programming.

8. Build Confidence

 Detailed explanations help you fully understand the solution,


boosting your confidence.

 You'll be ready to solve similar problems quickly and


efficiently.

9. Time Management

 The solutions are structured in a way that helps you learn how
to approach questions within a time limit.

 Helps improve your speed and efficiency during exams.

10. Ready for the Exam

 The structured approach of solving problems ensures you're


well-prepared for your exam.

 Improves your chances of scoring high by mastering key topics


and coding techniques.
TOP 10 Questions
Question 1
Write a Python function named countWordLines() that reads the
content of a text file named WORDS.TXT and counts how many
lines contain the word "Python".
For example, if the content of WORDS.TXT is as follows:
Python is a great programming language.
Many developers prefer Python for data analysis.
Learning Python can open many opportunities.
Coding in general is a valuable skill.
The function should display the following output:
Number of lines containing the word 'Python': 3

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.

The function should display:


Longest line: But some lines can be unexpectedly long and
descriptive, like this one!

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.

Then REVERSE.TXT should contain:


!dlrow ,olleH
.nuf si nohtyP
.gnidoc peeK

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!

Then SHORTLINES.TXT should contain:


This is a short line.
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.")

Quick Notes for Students:


1. Step-by-Step Explanation:
o Open the file:

 open("WORDS.TXT", "r"): Opens the file in read


mode.
o Read lines:
 file.readlines(): Gets all lines as a list.
o Search for the word:
 if "Python" in line: Checks if the word "Python" is in
the current line.
o Count matches:
 Increment count for every line that contains the

word.
2. Important Python Functions and Concepts:
o File Handling:
 Always use with open() to automatically close the

file after use.


o String Checking:
 "Python" in line: Checks if the word is part of a line.

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.")

Quick Notes for Students


1. Step-by-Step Explanation:
o Read content:

 content = infile.read(): Reads the entire content of


the file into a string.
o Replace text:
 content.replace("cloud", "sky"): Replaces all

occurrences of "cloud" with "sky".


o Write to output file:
 open("OUTPUT.TXT", "w"): Opens a new file (or
overwrites it) in write mode.
 outfile.write(modified_content): Writes the
modified content into the output file.
2. Important Python Functions and Concepts:
o String Replacement:

 str.replace("old", "new"): Replaces all occurrences


of old with new in a string.

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.")

Quick Notes for Students


1. Step-by-Step Explanation:
o Read all lines:

 file.readlines(): Reads all lines into a list. Each line is


a string.
o Find the longest line:
 max(lines, key=len): Finds the line with the maximum

length using the len function as the key.


o Print the result:
.strip(): Removes extra whitespace or newline
characters from the line before printing.
2. Important Python Functions and Concepts:
o Finding the Longest Line:
 max(iterable, key=function): Finds the maximum

item in a collection based on the given function (len


in this case).
o String Formatting:
 .strip(): Removes extra spaces or newline characters

for a clean output.

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.")

Quick Notes for Students


1. Step-by-Step Explanation:
o Read lines:
 lines = infile.readlines(): Reads all lines from the file

into a list, where each line is stored as a string.


o Reverse each line:
 line[::-1]: This is slicing with a step of -1, which

reverses the string (line) character by character.


o Write reversed lines:
 outfile.write(line[::-1] + "\n"): Writes the reversed
line to the new file with a newline character to
preserve line formatting.
2. Important Python Functions and Concepts:
o String Slicing:

 [::-1]: A powerful way to reverse a string in Python.


This is unique compared to replacing text or finding
max length.
o File Writing:
 Writing to a file using a loop to process and save

each modified line individually.

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.")

Quick Notes for Students


1. Step-by-Step Explanation:
o Filter lines by length:

 len(line.strip()): Calculates the length of the line


after removing leading and trailing whitespace using
.strip().
 if len(line.strip()) < 50: Checks if the length of the
line is less than 50 characters to decide whether to
save it.
2. Important Python Functions and Concepts:
o Conditional Writing:
 Lines are written to the new file only if they meet

the condition (length < 50).


o Whitespace Handling:
 .strip(): Ensures that empty spaces or newlines at

the start or end of a line donÕt affect the length


calculation.

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.")

Quick Notes for Students


1. Step-by-Step Explanation:
o Normalize content:
 content.lower(): Converts all text to lowercase to

ensure word matching is case-insensitive.


o Split into words:
 content.split(): Breaks the text into a list of words
using spaces as the delimiter.
o Clean punctuation:
 word.strip(".,!?"): Removes common punctuation from
words to ensure accurate counting.
o Count frequencies:
 frequency[word] = frequency.get(word, 0) + 1:

Updates the count for each word, using .get() to


initialize a new word with a count of 0.
2. Important Python Functions and Concepts:
o Dictionaries for Counting:

 A dictionary is used to store words as keys and


their occurrences as values, making it easy to track
and update frequencies.
o Sorting Keys:
 sorted(frequency): Outputs the words in
alphabetical order when displaying frequencies.

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.")

Quick Notes for Students


1. Step-by-Step Explanation:
o Add line numbers:
 enumerate(lines, start=1): Automatically assigns a

line number starting from 1 to each line in the file.


 f"{i}. {line}": Formats the line number and text into a
numbered format like 1. Line content.
o Write numbered lines:
 Each formatted line is written to the new file

NUMBERED.TXT.
2. Important Python Functions and Concepts:
o Enumerate:
 enumerate(iterable, start=n): Generates pairs of

index (starting from n) and item for each element in


the iterable. This avoids manually managing
counters.
o Formatted Strings:
 f"{i}. {line}": Used to create a clean and readable
format for numbered lines.

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.")

Quick Notes for Students


1. Step-by-Step Explanation:
o Open the File:

 with open("WORDS.TXT", "r") as file: Opens the


file WORDS.TXT in read mode, ensuring it is
automatically closed after processing.
o Read and Split Words:
 file.read().split(): Reads the file content and splits
it into a list of words based on whitespace.
o Identify Palindromes:
 [word for word in words if word == word[::-1]]: Uses

a list comprehension to find words that are the


same when reversed.
o Display Results:
 ', '.join(palindromes): Joins the palindromes into a

single string, separated by commas, for a clean


output.
2. Important Python Functions and Concepts:
o Context Manager:

 with open() as: Ensures the file is properly closed


after operations, even in case of errors.
o List Comprehension:
 [word for word in words if condition]: A compact
and efficient way to filter elements based on a
condition.
o String Slicing:
 word[::-1]: Reverses a string to check for
palindromes.

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:

 with open("FILE1.TXT", "r") as file1,

open("FILE2.TXT", "r") as file2: Opens FILE1.TXT


and FILE2.TXT in read mode simultaneously,
ensuring both are closed properly after processing.
o Read File Contents:
 file1.read() and file2.read(): Reads the full content
of each file into variables content1 and content2.
o Compare Contents:
 if content1 == content2: Checks if the content of

the two files is identical.


o Display Results:
 print("The files are identical."): Displays a success

message if the files match.


 print("The files are not identical."): Informs the
user if there is any difference.
2. Important Python Functions and Concepts:
o Context Manager:
 with open() as: Ensures files are automatically

closed after processing, even in the event of an


error.
o File Content Comparison:
 content1 == content2: A simple yet effective way to
compare the entire content of two files.

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.")

Quick Notes for Students


1. Step-by-Step Explanation:

o Open the File:

 with open("CONTACTS.TXT", "r") as file: Opens


CONTACTS.TXT in read mode, ensuring the file is
properly closed after processing.

o Read File Content:

 content = file.read(): Reads the entire content of the


file into a string for further processing.

o Extract Email Addresses:

 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 Display Extracted Emails:

 If emails are found, prints each email on a new line.

 If no emails are found, displays an appropriate message:


"No emails found in the file."
2. Error Handling:

o File Not Found Exception:

 except FileNotFoundError: Catches the exception if


CONTACTS.TXT is missing and prints a user-friendly
error message.

3. Important Python Functions and Concepts:

o Regular Expressions:

 re.findall(pattern, string): Searches the string for all


matches of the given pattern and returns them as a list.

o Regex Pattern for Emails:

 [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}:
Matches typical email address formats.

o Context Manager:

 with open() as: Ensures the file is closed properly after


processing, even in case of errors.

o Exception Handling:

 try...except: Handles missing files gracefully to prevent


program crashes.

You might also like