Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
120 views

Ch-5 - File Handling

Uploaded by

Prashant Mishra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

Ch-5 - File Handling

Uploaded by

Prashant Mishra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Ch.

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

A file sports.dat contains information in following format:


Event - Participant
Write a function that would read contents from file sports.dat and
creates a file named Atheletic.dat copying only those records from
sports.dat where the event name is "Atheletics".
Answer
Let the file "sports.dat" include the following sample records:
Athletics - Rahul
Swimming - Tanvi
Athletics - Akash
Cycling - Kabir
Athletics - Riya
def filter_records(input_file, output_file):
with open(input_file, 'r') as f_in:
with open(output_file, 'w') as f_out:
for line in f_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
with open("telephone.txt", "r") as file:
f = file.readlines()
for line in f:
name, number = line.split()
print(name, '\t\t' ,number)

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

with open("Poem.txt", 'r') as file:


for line in file:
words = line.split()
for word in words:
if word.lower() == 'to':
to_count += 1
elif word.lower() == 'the':
the_count += 1
print("count of 'to': ", to_count)
print("count of 'the': ", the_count)

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.
def AMCount(file_path):
count_a = 0
count_m = 0
with open(file_path, 'r') as file:
ch = ' '
while ch:
ch = file.read(1)
ch_low = ch.lower()
if ch_low == 'a':
count_a += 1
elif ch_low == 'm':
count_m += 1

print("A or a:", count_a)


print("M or m:", count_m)

AMCount("STORY.TXT")

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.
with open("Article.txt", 'r') as file:
text = file.read()
count = 0
for char in text:
if char.isupper():
count += 1

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())

source_file = input("Enter the name of the source file: ")


destination_file = input("Enter the name of the destination file:
")

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
def append_file(f1, f2):
with open(f1, 'r') as source:
with open(f2, 'a') as destination:
destination.write(source.read())

source_file = input("Enter the name of the source file: ")


destination_file = input("Enter the name of the destination file:
")

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

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
def DISPLAYWORDS(file_name):
with open(file_name, 'r') as file:
for line in file:
words = line.split()
for word in words:
if len(word) < 4:
print(word)
for line in file:
words = line.split()
for word in words:
if len(word) < 4:
print(word)

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

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.
def count_lines(file_name):
count = 0
with open(file_name, 'r') as file:
for line in file:
if line.strip().startswith('A'):
count += 1
print(count)

count_lines("LINES.TXT")

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
with open("myfile.txt", 'r') as file:
while True:
char = file.read(1)
if char == '$' or not char:
break
count += 1
print(count)

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

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

member1 = {'MemberNo.': '123456', 'Name': 'Pranav'}


member2 = {'MemberNo.': '456235', 'Name': 'Aman'}

def write_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

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

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

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

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, Aravind Adiga, 49.5]
Book4 = [1002, The Satanic Verses, Salman Rushdie, 39.23]
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))

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.
def Show_words(file_name):
with open(file_name, 'r') as file:
for line in file:
words = line.strip().split()
if len(words) == 5:
print(line.strip())

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

with open("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
import csv

def write_nested_list(data, file_name):


with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)

def read_csv(file_name):
with open(file_name, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)

nested_list = [['Name', 'Age', 'Gender'],


['Prateek', '14', 'Male'],
['Ananya', '24', 'Female'],
['Aryan', '44', 'Male']]

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

def change_delimiter(input_file, output_file, input_delimiter,


output_delimiter):
with open(input_file, 'r', newline='') as f_in:
reader = csv.reader(f_in, delimiter = input_delimiter)
data = list(reader)

with open(output_file, 'w', newline='') as f_out:


writer = csv.writer(f_out, delimiter = output_delimiter)
writer.writerows(data)

change_delimiter('original.csv', 'modified.csv', ',', '|')


Contents of "modified.csv":
Product|Price|Quantity
Apple|1.99|100
Banana|0.99|150
Orange|2.49|80

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

def filter(input_file, output_file):


with open(input_file, 'r', newline='') as f_in,
open(output_file, 'w', newline='') as f_out:
reader = csv.reader(f_in)
writer = csv.writer(f_out)

for row in reader:


if not row[0].startswith('check'):
writer.writerow(row)

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():

with open('furdata.csv', mode='a', newline='') as file:


writer = csv.writer(file)
fid = input("Enter furniture id: ")
fname = input("Enter furniture name: ")
fprice = float(input("Enter furniture price: "))
writer.writerow([fid, fname, fprice])
print("Record added successfully to 'furdata.csv'")

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()

You might also like