Ch-5 - File Handling
Ch-5 - File Handling
5: File Handling_Type : C
Question 1
Write a program that reads a text file and creates another file that is
identical except that every sequence of consecutive blank spaces is
replaced by a single space.
Answer
Let the file "input.txt" include the following sample text:
In the beginning there was chaos.
Out of the chaos came order.
The universe began to take shape.
Stars formed and galaxies were born.
Life emerged in the vast expanse.
with open("input.txt", 'r') as f:
with open("output.txt", 'w') as fout:
for line in f:
modified_line = ' '.join(line.split())
fout.write(modified_line + '\n')
Question 2
Question 3
Question 4
Write a program to count the words "to" and "the" present in a text
file "Poem.txt".
Answer
Let the file "Poem.txt" include the following sample text:
To be or not to be, that is the question.
The quick brown fox jumps over the lazy dog.
To infinity and beyond!
The sun sets in the west.
To be successful, one must work hard.
to_count = 0
the_count = 0
Question 5
AMCount("STORY.TXT")
Question 6
print(count)
Question 7
Write a program that copies one file to another. Have the program
read the file names from user?
Answer
def copy_file(file1, file2):
with open(file1, 'r') as source:
with open(file2, 'w') as destination:
destination.write(source.read())
copy_file(source_file, destination_file)
Question 8
append_file(source_file, destination_file)
Question 9
Write a method in python to read lines from a text file
MYNOTES.TXT, and display those lines, which are starting with an
alphabet 'K'.
Answer
Let the file "MYNOTES.TXT" include the following sample text:
Kangaroo is a mammal native to Australia.
Lion is a large carnivorous.
Koala is an arboreal herbivorous.
Elephant is a large herbivorous mammal.
def display_lines(file_name):
with open(file_name, 'r') as file:
line = file.readline()
while line:
if line.strip().startswith('K'):
print(line.strip())
line = file.readline()
display_lines("MYNOTES.TXT")
Question 10
DISPLAYWORDS("STORY.TXT")
Question 11
Write a program that reads characters from the keyboard one by
one. All lower case characters get stored inside the file LOWER, all
upper case characters get stored inside the file UPPER and all other
characters get stored inside file OTHERS.
Answer
lower_file = open("LOWER.txt", 'w')
upper_file = open("UPPER.txt", 'w')
others_file = open("OTHERS.txt", 'w')
ans = 'y'
while ans == 'y':
char = input("Enter a character: ")
if char.islower():
lower_file.write(char + "\n")
elif char.isupper():
upper_file.write(char + "\n")
else:
others_file.write(char + "\n")
ans = input("Want to enter a character? (y/n): ")
lower_file.close()
upper_file.close()
others_file.close()
Question 12
count_lines("LINES.TXT")
Question 13
Question 14
Write a program that will create an object called filout for writing,
associate it with the filename STRS.txt. The code should keep on
writing strings to it as long as the user wants.
Answer
with open('STRS.txt', 'w') as filout:
ans = 'y'
while ans == 'y':
string = input("Enter a string: ")
filout.write(string + "\n")
ans = input("Want to enter more strings?(y/n)...")
Question 15
def write_member():
file = open("member.dat", 'wb')
pickle.dump(member1, file)
pickle.dump(member2, file)
file.close()
write_member()
Question 16
def search_and_display_staff(staff_code):
found = False
try:
file = open("staff.dat", "rb")
while True:
staff_data = pickle.load(file)
if staff_data['Staffcode'] == staff_code:
print("Staffcode:", staff_data['Staffcode'])
print("Name:", staff_data['Name'])
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
search_and_display_staff('S0105')
Question 17
Considering the following definition of dictionary COMPANY, write a
method in Python to search and display the content in a pickled file
COMPANY.DAT, where CompID key of the dictionary is matching
with the value '1005'.
Company = {'CompID' = ........., 'CName' = ........., 'Turnover'
= .........}
Answer
Let the file "COMPANY.DAT" include following data:
Company1 = {'CompID': '1001', 'CName': 'ABC', 'Turnover': 500000}
Company2 = {'CompID': '1003', 'CName': 'DEF', 'Turnover': 600000}
Company3 = {'CompID': '1005', 'CName': 'LMN', 'Turnover': 900000}
import pickle
def company(comp_id):
found = False
try:
file = open("COMPANY.DAT", "rb")
while True:
company_data = pickle.load(file)
if company_data['CompID'] == comp_id:
print("Company ID:", company_data['CompID'])
print("Company Name:", company_data['CName'])
print("Turnover:", company_data['Turnover'])
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
company('1005')
Question 18
def search_trains():
found = False
try:
file = open("TRAIN.DAT", "rb")
while True:
trains = pickle.load(file)
if trains['To'] == "Delhi":
print("Train no: ", trains['Tno'])
print("From: ", trains['From'])
print("To: ", trains['To'])
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
search_trains()
Question 19
def CountRec(authorName):
count = 0
found = False
try:
file = open("Book.dat", "rb")
while True:
record = pickle.load(file)
if record[2] == authorName:
count += 1
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search successful")
file.close()
return count
CreateFile()
author = input("Enter Author name to count books: ")
print("Number of books by", author, ":", CountRec(author))
Question 20
Show_words('NOTES.TXT')
Question 21
Write a Python program to read a given CSV file having tab delimiter.
Answer
Let "example.csv" file contain the following data:
Name Age Gender
Kavya 25 Female
Kunal 30 Male
Nisha 28 Female
import csv
Output
['Name Age Gender']
['Kavya 25 Female']
['Kunal 30 Male']
['Nisha 28 Female']
Question 22
def read_csv(file_name):
with open(file_name, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
write_nested_list(nested_list, 'output.csv')
print("Content of 'output.csv':")
read_csv('output.csv')
Question 23
Write a function that reads a csv file and creates another csv file with
the same content, but with a different delimiter.
Answer
Let "original.csv" file contain the following data:
Product,Price,Quantity
Apple,1.99,100
Banana,0.99,150
Orange,2.49,80
import csv
Question 24
Write a function that reads a csv file and creates another csv file with
the same content except the lines beginning with 'check'.
Answer
Let "input.csv" file contain the following data:
check1,10,A
check2,20,B
data1,30,C
check3,40,D
data2,50,E
import csv
filter('input.csv', 'output.csv')
Contents of "output.csv":
data1,30,C
data2,50,E
Question 25
Give any one point of difference between a binary file and a CSV file.
Write a Program in Python that defines and calls the following user
defined functions :
(a) add(). To accept and add data of an employee to a CSV file
'furdata.csv'. Each record consists of a list with field elements as fid,
fname and fprice to store furniture id, furniture name and furniture
price respectively.
(b) search(). To display the records of the furniture whose price is
more than 10000.
Answer
The difference between a binary file and CSV file is that binary files
are used for storing complex data in a non-human-readable format
and they store data in a sequence of bytes, while CSV files are plain
text files used for storing structured tabular data in a human-readable
text format.
Let the file "furdata.csv" include following data:
[1, table, 20000]
[2, chair, 12000]
[3, board, 10000]
import csv
def add():
def search():
found = False
with open('furdata.csv', mode='r') as file:
reader = csv.reader(file)
print("Records of furniture with price more than 10000:")
for row in reader:
if len(row) == 3 and float(row[2]) > 10000:
print("Furniture ID:", row[0])
print("Furniture Name:", row[1])
print("Furniture Price:", row[2])
print()
found = True
if found == False:
print("No records of furniture with price more than 10000
found")
add()
search()