File Handing Practical
File Handing Practical
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.
withopen("input.txt", 'r') as f:
withopen("output.txt", 'w') asfout:
for line in f:
modified_line=' '.join(line.split())
fout.write(modified_line+'\n')
or
p1=open("input.txt", 'r')
p2=open("input.txt", 'w')
lst=p1.readlines() # returns a list of strings, each line is a string
for line in f: # iterate through each line
words=line.split() # split the string (each line) into list of words,
separator is whitespace [one or more]
f2.write(" ".join(words)+"\n") # The join() method takes all items
from a list(or any iterable object) and
joins them into one string, using a
deffilter_records(input_file, output_file):
withopen(input_file, 'r') asf_in:
withopen(output_file, 'w') asf_out:
for line inf_in:
event, participant =line.strip().split(' - ')
if event =='Athletics':
f_out.write(line)
filter_records('sports.dat', 'Athletic.dat')
Question 3
A file contains a list of telephone numbers in the following form:
Arvind 7258031
Sachin 7259197
The names contain only one word, the names and telephone numbers are
separated by white spaces. Write program to read a file and display its contents in
two columns.
Answer
Let the file "telephone.txt" include the following sample records:
Arvind 7258031
Sachin 7259197
Karuna 8479939
withopen("telephone.txt", "r") as file:
f =file.readlines()
for line in f:
name, number =line.split()
print(name, '\t\t' ,number)
Output
Arvind 7258031
Sachin 7259197
Karuna 8479939
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
Output
count of 'to': 4
count of 'the': 5
Question 5
Write a function AMCount() in Python, which should read each character of a text
file STORY.TXT, should count and display the occurrence of alphabets A and M
(including small cases a and m too).
Example :
If the file content is as follows :
Updated information
As simplified by official websites.
The EUCount() function should display the output as :
A or a : 4
M or m : 2
Answer
Let the file "STORY.TXT" include the following sample text:
Updated information
As simplified by official websites.
defAMCount(file_path):
count_a=0
count_m=0
withopen(file_path, 'r') as file:
ch=' '
whilech:
ch=file.read(1)
ch_low=ch.lower()
ifch_low=='a':
count_a+=1
elifch_low=='m':
count_m+=1
AMCount("STORY.TXT")
Output
A or a: 4
M or m: 2
Question 6
Write a program to count the number of upper-case alphabets present in a text file
"Article.txt".
Answer
Let the file "Article.txt" include the following sample text:
PYTHON is a Popular Programming Language.
withopen("Article.txt", 'r') as file:
text=file.read()
count=0
for char in text:
ifchar.isupper():
count+=1
print(count)
Output
9
Question 7
Write a program that copies one file to another. Have the program read the file
names from user ?
Answer
defcopy_file(file1, file2):
withopen(file1, 'r') as source:
withopen(file2, 'w') as destination:
destination.write(source.read())
copy_file(source_file, destination_file)
Question 8
Write a program that appends the contents of one file to another. Have the
program take the filenames from the user.
Answer
defappend_file(f1, f2):
withopen(f1, 'r') as source:
withopen(f2, 'a') as destination:
destination.write(source.read())
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.
defdisplay_lines(file_name):
withopen(file_name, 'r') as file:
line=file.readline()
while line:
ifline.strip().startswith('K'):
print(line.strip())
line=file.readline()
display_lines("MYNOTES.TXT")
Output
Kangaroo is a mammal native to Australia.
Koala is an arboreal herbivorous.
Question 10
Write a method/function DISPLAYWORDS() in python to read lines from a text file
STORY.TXT, and display those words, which are less than 4 characters.
Answer
Let "STORY.TXT" file contain the following text:
Once upon a time, there was a little boy named Jay
He had a dog named Leo
defDISPLAYWORDS(file_name):
withopen(file_name, 'r') as file:
for line in file:
words=line.split()
for word in words:
iflen(word) <4:
print(word)
for line in file:
words=line.split()
for word in words:
iflen(word) <4:
print(word)
DISPLAYWORDS("STORY.TXT")
Output
a
was
a
boy
Jay
He
had
a
dog
Leo
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'
whileans=='y':
char=input("Enter a character: ")
ifchar.islower():
lower_file.write(char +"\n")
elifchar.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()
Output
Enter a character: e
Want to enter a character? (y/n): y
Enter a character: A
Want to enter a character? (y/n): y
Enter a character: D
Want to enter a character? (y/n): y
Enter a character: c
Want to enter a character? (y/n): y
Enter a character: 7
Want to enter a character? (y/n): y
Enter a character: @
Want to enter a character? (y/n): n
The file "LOWER.txt" includes:
e
c
The file "UPPER.txt" includes:
A
D
The file "OTHERS.txt" includes:
7
@
Question 12
Write a function in Python to count and display the number of lines starting with
alphabet 'A' present in a text file "LINES.TXT". e.g., the file "LINES.TXT" contains
the following lines:
A boy is playing there.
There is a playground.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.
the function should display the output as 3.
Answer
The file "LINES.TXT" contains the following lines:
A boy is playing there.
There is a playground.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.
defcount_lines(file_name):
count=0
withopen(file_name, 'r') as file:
for line in file:
ifline.strip().startswith('A'):
count+=1
print(count)
count_lines("LINES.TXT")
Output
3
Question 13
Write a program that counts the number of characters up to the first $ in a text file.
Answer
Let the sample file "myfile.txt" contain the following text:
Hello world! This is a test file.
It contains some characters until the first $ is encountered.
count=0
withopen("myfile.txt", 'r') as file:
whileTrue:
char=file.read(1)
if char =='$'ornot char:
break
count+=1
print(count)
Output
78
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
withopen('STRS.txt', 'w') asfilout:
ans='y'
whileans=='y':
string=input("Enter a string: ")
filout.write(string +"\n")
ans=input("Want to enter more strings?(y/n)...")
Output
Enter a string: Hello
Want to enter more strings?(y/n)...y
Enter a string: world!
Want to enter more strings?(y/n)...n
The file "STRS.txt" includes:
Hello
world!
Question 15
Consider the following definition of a dictionary Member, write a method in Python
to write the content in a pickled file member.dat.
Member = {'MemberNo.': ..............., 'Name': ...............}
Answer
import pickle
defwrite_member():
file=open("member.dat", 'wb')
pickle.dump(member1, file)
pickle.dump(member2, file)
file.close()
write_member()
Question 16
Consider the following definition of dictionary Staff, write a method in python to
search and display content in a pickled file staff.dat, where Staffcode key of the
dictionary is matching with 'S0105'.
Staff = {'Staffcode': ..............., 'Name' = ...............}
Answer
Let the file "staff.dat" include following data:
Staff1 = {'Staffcode': 'S0102', 'Name': 'Sanya'}
Staff2 = {'Staffcode': 'S0104', 'Name': 'Anand'}
Staff3 = {'Staffcode': 'S0105', 'Name': 'Aditya'}
import pickle
defsearch_and_display_staff(staff_code):
found=False
try:
file=open("staff.dat", "rb")
whileTrue:
staff_data=pickle.load(file)
ifstaff_data['Staffcode'] ==staff_code:
print("Staffcode:", staff_data['Staffcode'])
print("Name:", staff_data['Name'])
found=True
exceptEOFError:
if found ==False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
search_and_display_staff('S0105')
Output
Staffcode: S0105
Name: Aditya
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
defcompany(comp_id):
found=False
try:
file=open("COMPANY.DAT", "rb")
whileTrue:
company_data=pickle.load(file)
ifcompany_data['CompID'] ==comp_id:
print("Company ID:", company_data['CompID'])
print("Company Name:", company_data['CName'])
print("Turnover:", company_data['Turnover'])
found=True
exceptEOFError:
if found ==False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
company('1005')
Output
Company ID: 1005
Company Name: LMN
Turnover: 900000
Question 18
Write a function to search and display details of all trains, whose destination is
"Delhi" from a binary file "TRAIN.DAT". Assuming the binary file is containing the
objects of the following dictionary type:
Train = {'Tno': ..............., 'From': ...............,'To': ...............}
Answer
Let the dictionary contained in file "TRAIN.DAT" be as shown below:
Train1 = {'Tno': '1234', 'From': 'Mumbai', 'To': 'Delhi'}
Train2 = {'Tno': '5678', 'From': 'Chennai', 'To': 'Delhi'}
Train3 = {'Tno': '9012', 'From': 'Kolkata', 'To': 'Mumbai'}
Train4 = {'Tno': '3456', 'From': 'Delhi', 'To': 'Bangalore'}
Train5 = {'Tno': '7890', 'From': 'Pune', 'To': 'Delhi'}
import pickle
defsearch_trains():
found=False
try:
file=open("TRAIN.DAT", "rb")
whileTrue:
trains=pickle.load(file)
if trains['To'] =="Delhi":
print("Train no: ", trains['Tno'])
print("From: ", trains['From'])
print("To: ", trains['To'])
found=True
exceptEOFError:
if found ==False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
search_trains()
Output
Train no: 1234
From: Mumbai
To: Delhi
Train no: 5678
From: Chennai
To: Delhi
Train no: 7890
From: Pune
To: Delhi
Search Successful
Question 19
A binary file "Book.dat" has structure [BookNo, Book_Name, Author, Price].
(i) Write a user defined function CreateFile() to input data for a record and add to
Book.dat.
(ii) Write a function CountRec(Author) in Python which accepts the Author name
as parameter and count and return number of books by the given Author are
stored in the binary file "Book.dat"
Answer
Let the file "Book.dat" include following data:
Book1 = [1001, Midnight's Children, Salman Rushdie, 29.99]
Book2 = [1004, A Suitable Boy, Vikram Seth, 59.9]
Book3 = [1003, The White Tiger, AravindAdiga, 49.5]
Book4 = [1002, The Satanic Verses, Salman Rushdie, 39.23]
import pickle
defCreateFile():
file=open("Book.dat", "ab")
BookNo=int(input("Enter Book Number: "))
Book_Name=input("Enter Book Name: ")
Author=input("Enter Author Name: ")
Price=float(input("Enter Price: "))
record= [BookNo, Book_Name, Author, Price]
pickle.dump(record, file)
file.close()
defCountRec(authorName):
count=0
found=False
try:
file=open("Book.dat", "rb")
whileTrue:
record=pickle.load(file)
if record[2] ==authorName:
count+=1
found=True
exceptEOFError:
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))
Output
Enter Book Number: 1008
Enter Book Name: Three Thousand Stiches
Enter Author Name: SudhaMurty
Enter Price: 200
Enter Author name to count books: Salman Rushdie
Search successful
Number of books by Salman Rushdie : 2
Question 20
Write a function Show_words() in python to read the content of a text file
'NOTES.TXT' and display only such lines of the file which have exactly 5 words in
them.
Example, if the file contains :
This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.
Then the function should display the output as :
This is a sample file.
The file contains many sentences.
Answer
The file "NOTES.TXT" contains:
This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.
defShow_words(file_name):
withopen(file_name, 'r') as file:
for line in file:
words=line.strip().split()
iflen(words) ==5:
print(line.strip())
Show_words('NOTES.TXT')
Output
This is a sample file.
The file contains many sentences.
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
importcsv
withopen("example.csv", 'r', newline='') as file:
reader=csv.reader(file, delimiter='\t')
for row in reader:
print(row)
Output
['Name Age Gender']
['Kavya 25 Female']
['Kunal 30 Male']
['Nisha 28 Female']
Question 22
Write a Python program to write a nested Python list to a csv file in one go. After
writing the CSV file read the CSV file and display the content.
Answer
importcsv
defwrite_nested_list(data, file_name):
withopen(file_name, 'w', newline='') as file:
writer=csv.writer(file)
writer.writerows(data)
defread_csv(file_name):
withopen(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')
Output
['Name', 'Age', 'Gender']
['Prateek', '14', 'Male']
['Ananya', '24', 'Female']
['Aryan', '44', 'Male']
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
importcsv
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
importcsv
deffilter(input_file, output_file):
withopen(input_file, 'r', newline='') asf_in, open(output_file, 'w', newline='')
asf_out:
reader=csv.reader(f_in)
writer=csv.writer(f_out)
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]
importcsv
defadd():
defsearch():
found=False
withopen('furdata.csv', mode='r') as file:
reader=csv.reader(file)
print("Records of furniture with price more than 10000:")
for row in reader:
iflen(row) ==3andfloat(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()
Output
Enter furniture id: 9
Enter furniture name: desk
Enter furniture price: 3000
Record added successfully to 'furdata.csv'
Records of furniture with price more than 10000:
Furniture ID: 1
Furniture Name: table
Furniture Price: 20000
Furniture ID: 2
Furniture Name: chair
Furniture Price: 12000
(i) Write a user defined function CreateFile() to input data for a record and add to Book.dat.
(ii) Write a function CountRec(Author) in Python which accepts the Author name as parameter
and count and return number of books by the given Author are stored in the binary file
"Book.dat"
import pickle
def CreateFile():
file = open("Book.dat", "ab")
BookNo = int(input("Enter Book Number: "))
Book_Name = input("Enter Book Name: ")
Author = input("Enter Author Name: ")
Price = float(input("Enter Price: "))
record = [BookNo, Book_Name, Author, Price]
pickle.dump(record, file)
file.close()
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))