File Handling (FINAL)
File Handling (FINAL)
File Handling (FINAL)
Sc Practical
CODE :
def record():
f=open("record.txt","r")
a=""
while True:
a=f.readline()
for i in a.split():
print(i,end="#")
if a!="":
print()
f.close()
record()
OUTPUT:
#2 Read a txt file and display the number
of vowels/digit/uppercase/lowercase characters in
a file.
CODE :
def case():
file=open("record.txt","r")
a=""
vowels=0
digits=0
uppercase=0
lowercase=0
a=file.read()
if a!="":
for i in range(len(a)):
if a[i] in 'AEIOUaeiou':
vowels=vowels+1
if a[i].isdigit():
digits=digits+1
if a[i].isupper():
uppercase=uppercase+1
if a[i].islower():
lowercase=lowercase+1
print(a)
print("No. of vowels is :",vowels)
print("No. of digits is :",digits)
print("No. of uppercase letters is :",uppercase)
print("No. of lowercase letters is :",lowercase)
file.close()
case()
OUTPUT:
#3 Remove all the lines that contain the character ‘a’
in a file and write it to another file.
CODE :
import os
fr=open("record.txt","r")
fw=open("Newfile.txt","w")
fw1=open("temp.txt",'w')
for i in fr.readlines():
if 'a' in i or 'A' in i:
fw.write(i)
fw.write("\n")
else:
fw1.write(i)
fr.close()
fw1.close()
os.remove("record.txt")
os.rename("temp.txt","Character.txt")
fw.close()
OUTPUT :
#4 Count lines, characters and words of a text file.
CODE:
def count():
f=open("record.txt", "r")
st=" "
line_count=-1
char_count=0
word_count=0
while st:
st=f.readline()
print(st)
line_count=line_count+1
l=st.split()
word_count=word_count+len(l)
for i in l:
char_count=char_count+len(i)
print("The number of lines in the file are: ", line_count)
print("The number of characters in the file are: ", char_count)
print("The number of words in the file are: ", word_count)
f.close()
count()
OUTPUT :
#5 Merge the contents of two text file
into another file.
CODE:
def merge():
f1=open("record.txt","r")
f2=open("record2.txt","r")
f3=open("FinRec.txt","a")
ch1=""
ch2=""
f4=0
ch1=f1.read()
ch2=f2.read()
f3.write(ch1+'\n')
f3.write(ch2)
f1.close()
f2.close()
f3.close()
merge()
OUTPUT:
#6 Delete a student record from student.txt file. If
record is not there then, display appropriate
message.(Fields are roll_no,student_name,marks)
CODE:
def delete():
r=input("Enter Roll.No :")
f=open("StudRec.txt","r")
ch=f.readlines()
a=0
f=open("StudRec.txt","w")
for i in ch:
s=i.split(" ")
if s[0]==r:
a=1
else:
f.write(i)
if a==1:
print("Record Deleted successfully.")
else:
print("Record not found.")
delete()
OUTPUT:
CODE:
def update():
count=0
f=open("StudRec.txt", "r")
roll=int(input("Enter the Roll Number: "))
ch=f.readlines()
f.close()
f1=open("StudRec.txt", "w")
for i in ch:
if i[1] == " "or i[1] == ",":
if i[0] == str(roll):
roll_no=int(input("Enter new roll number: "))
student_name=input("Enter new name: ")
marks=int(input("Enter new marks: "))
r=str(roll_no)+" "+student_name+" "+str(marks)+"\n"
f1.write(r)
count=count+1
else:
f1.write(i)
else:
if int(i[0]+i[1])==int(roll):
roll_no=int(input("Enter new roll number: "))
student_name=input("Enter new name: ")
marks=int(input("Enter new marks: "))
r=str(roll_no)+" "+student_name+" "+str(marks)+"\n"
f1.write(r)
count=count+1
else:
f1.write(i)
update()
OUTPUT:
CODE:
def topper():
f=open("StudRec.txt", "r")
f1=open("above90.txt", "w")
l=f.readlines()
for i in l:
i=i.strip("\n")
if int(i[-2:])>90:
f1.write(i+"\n")
topper()
OUTPUT:
#9 A binary file “Book.dat” has structure [BookNo,
Book_Name, Author, Price].
1) Write a user defined function CreateFile()
to input data for a record and add to
Book.dat .
2) Write a function Countrec(Author) in Python
which accepts the Author name as parameter and
count and return the number of books by the
given author are stored in the binary file.
CODE:
import pickle
def CreateFile():
bk={}
Book=open('Book.dat','wb')
a='y'
while a=='y':
bk['BookNo']=int(input("Enter book number :"))
bk['Book_Name']=input("Enter book name :")
bk['Author']=input("Enter Author name :")
bk['Price']=float(input("Enter book price :"))
pickle.dump(bk,Book)
a=input("Wish to continue :")
Book.close()
def CountRec(Author):
f=open('Book.dat','rb')
d={}
try:
count=0
while True:
d=pickle.load(f)
if d['Author']==Author:
count=count+1
except EOFError:
f.close()
print("No. of books in the records written by",Author,"is :",count)
CreateFile()
x=input("Enter the Name of Author :")
CountRec(x)
OUTPUT:
i)
ii)
#10 Write a Python function to increase the price of a product by 10% from
“product.csv” file against a product ‘Fan’. Format of the ‘product.dat’ file is
[product_id,product_name,price].
CODE:
import os
import csv
def price():
f=open('Product.csv','w')
a='y'
w=csv.writer(f)
l=["Product_id","Product_Name","Price"]
w.writerow(l)
while a=='y':
Product_id=int(input("Enter the product id :"))
Product_Name=input("Enter Product Name :")
Price=float(input("Enter the price :"))
l=[Product_id,Product_Name,Price]
w.writerow(l)
a=input("Wish to continue :")
f.close()
def price_inc():
a=0
f1=open('Product.csv','r')
f2=open('temp.csv','w')
w=csv.reader(f1)
v=csv.writer(f2)
l1=[]
for i in w:
for j in i:
if j=='Fan':
i[2]= float(i[2])*1.1
a=1
v.writerow(i)
if a==1:
print('Price Updated successfully.')
f1.close()
f2.close()
os.remove('Product.csv')
os.rename('temp.csv','Product.csv')
price()
price_inc()
OUTPUT:
#11 Write a python function to calculate the
Average performance of a class and display the
name of the student who scored maximum marks
from “marks.csv” file, whose structure is as
follows: Roll_No, Name, Marks.
CODE:
import csv
def marks():
f=open('Marks.csv','w')
a='y'
w=csv.writer(f)
l=["Roll No.","Name","Marks"]
w.writerow(l)
while a=='y':
RollNo=int(input("Enter Roll No.:"))
Name=input("Name :")
Marks=int(input("Marks :"))
l=[RollNo,Name,Marks]
w.writerow(l)
a=input("Wish to continue :")
f.close()
def average():
f1=open('Marks.csv','r')
rd=csv.reader(f1)
sm=0
count=0
average=0
topper=""
mx=0
a=0
lst=[]
for i in rd:
for j in i:
if i[2] not in lst and i[2]!='Marks':
i[2]=int(i[2])
lst.append(i[2])
mx=max(lst)
a=1
if a==1:
for k in i:
if k==mx:
topper=i[1]
sm=sum(lst)
count=len(lst)
average=sm/count
print("The average performance of class is
:",average)
print(topper,"scored maximum marks in the class,
which is",mx,"out of 100.")
f1.close()
marks()
average()
OUTPUT:
#12 Write Python function to count total no. of records present in “data.csv” file
CODE:
import csv
def datafile():
f=open('data.csv','w')
a='y'
w=csv.writer(f)
l=["Roll No.","Name"]
w.writerow(l)
while a=='y':
RollNo=int(input("Enter Roll No. :"))
Name=input("Name :")
l=[RollNo,Name]
w.writerow(l)
a=input("Wish to continue :")
f.close()
def datacount():
f1=open('data.csv','r')
rd=csv.reader(f1)
lst=[]
count=0
for i in rd:
for j in i:
if i[0]!='Roll No.' and i[0] not in lst:
lst.append(i[0])
count=len(lst)
print("The total No.is ",count)
f1.close()
datafile()
datacount()
OUTPUT:
#13 A binary file “STUDENT.DAT” has structure
(admission_number, Name, Percentage). Write a
function countrec() in Python that would read contents
of the file “STUDENT.DAT” and copy the details of
those students whose percentage is above 75 into
“75.dat” file. Also display number of
students scoring above 75%
CODE:
import pickle
def Filecreate():
st={}
Stu=open('Student.dat','wb')
a='y'
while a=='y':
st['Admission No.']=int(input("Enter student admission no.:"))
st['Name']=input("Enter Name :")
st['Percentage']=float(input("Enter percentange :"))
pickle.dump(st,Stu)
a=input("Wish to continue :")
Stu.close()
def countrec():
Stu1=open('Student.dat','rb')
f=open('75.dat','wb')
d={}
try:
count=0
while True:
d=pickle.load(Stu1)
if d['Percentage']>75:
pickle.dump(d,f)
count=count+1
except EOFError:
f.close()
Stu1.close()
print("No. of students who scored above 75 are",count)
Filecreate()
countrec()
OUTPUT:
#14 Write a function routechange(route_number)
which takes the Route number as parameter and
modify the route name(Accept it from the user)
of passed route number in a binary file
“route.dat”.
CODE:
import pickle
def createfile():
rt={}
Route=open('Route.dat','wb')
a='y'
while a=='y':
rt['Route_No.']=int(input("Enter route number :"))
rt['Route_Name']=input("Enter route name :")
pickle.dump(rt,Route)
a=input("Wish to continue :")
Route.close()
def routechange(route_number):
f=open('route.dat','rb+')
d={}
rtnm=input("Enter route name to be changed :")
try:
while True:
pos=f.tell()
d=pickle.load(f)
if d['Route_No.']==route_number:
d['Route_Name']=rtnm
f.seek(pos)
pickle.dump(d,f)
print("Record updated successfully.")
except EOFError:
f.close()
createfile()
x=int(input("Enter the route number to be modified :"))
routechange(x)
OUTPUT:
#15 Write python function to merge the contents
of “one.csv” and “two.csv” files into
“third.csv” file.
CODE:
import csv
def create_file1():
f=open('one.csv','w')
a='y'
w=csv.writer(f)
l=["Roll no.","Name"]
w.writerow(l)
while a=='y':
RollNo=int(input("Enter Roll No. for one:"))
Name=input("Name for one :")
l=[RollNo,Name]
w.writerow(l)
a=input("Wish to continue :")
f.close()
def create_file2():
f1=open('two.csv','w')
a='y'
v=csv.writer(f1)
l=["Roll no.","Name"]
v.writerow(l)
while a=='y':
RollNo1=int(input("Enter Roll No. for two:"))
Name1=input("Name for two :")
l1=[RollNo1,Name1]
v.writerow(l1)
a=input("Wish to continue :")
f1.close()
def merger():
f2=open('one.csv','r')
f3=open('two.csv','r')
f4=open('third.csv','w')
r1=csv.reader(f2)
r2=csv.reader(f3)
wt=csv.writer(f4)
for i in r1:
wt.writerow(i)
for j in r2:
wt.writerow(j)
print("Merged Successfully.")
f2.close()
f3.close()
f4.close()
create_file1()
create_file2()
merger()
OUTPUT:
#16 Write python function to delete records of
students who scored less than 33 in an exam. Data
is stored in “Exam.csv” file having fields as
Roll_No, Name, Marks. Display error message
“Record not present”, in case no student has
scored less than 33 marks.
CODE:
import csv
import os
def create_file():
f=open('Exam.csv','w')
a='y'
w=csv.writer(f)
while a=='y':
RollNo=int(input("Enter Roll No.:"))
Name=input("Name :")
Marks=int(input("Marks :"))
l=[RollNo,Name,Marks]
w.writerow(l)
a=input("Wish to continue :")
f.close()
def fail():
f1=open('Exam.csv','r')
f2=open('temp.csv','w')
rd=csv.reader(f1)
lst=list(rd)
wr=csv.writer(f2)
x=0
n=0
for i in lst:
if i!=[]:
if i[2]!='Marks':
x=int(i[2])
i[2]=x
if x>33:
wr.writerow(i)
n=1
if n==1:
print("Record Deleted successfully.")
f1.close()
f2.close()
os.remove("Exam.csv")
os.rename("temp.csv","Exam.csv")
else:
print('Record not present.')
create_file()
fail()
OUTPUT:
#17 Amit is a monitor of XII-A and he stored the
record of all the students of his class named
‘class.dat’. Structure of record is [roll number,
name, percentage]. His computer teacher assigned
the following duty to Amit. Write a function
remcount() to count the number of students who
need remedial class(students who scored less than
40 percent).
CODE:
import pickle
def createfile():
f=open("class.dat", "wb")
lst=[]
a="y"
while a== "y":
roll_number = int(input("Enter Roll Number: "))
name = input("Enter Name: ")
percentage = int(input("Enter Percentage: "))
lst=[roll_number,name,percentage]
pickle.dump(lst,f)
a=input("Wish to continue : ")
f.close()
def remcount():
count=0
f1=open("class.dat", 'rb')
try:
while True:
rd=pickle.load(f1)
if len(rd)>0 and rd[2]<40:
count=count+1
except EOFError:
f1.close()
print("The number of students who require remedial classes are : ",count)
createfile()
remcount()
OUTPUT:
#18 A binary file ‘emp.dat’ has structure [employee
id, employee name]. Write a function
delrec(employee_number) in Python that would
read contents of the file “emp.dat” and delete the
details of those employees whose employee number is
passed as an argument.
CODE:
import pickle
import os
def createfile():
emp={}
employee=open('emp.dat','wb')
a='y'
while a=='y':
emp['employee_id']=int(input("Enter employee id:"))
emp['employee_Name']=input("Enter employee name :")
pickle.dump(emp,employee)
a=input("Wish to continue :")
employee.close()
def delrec(employee_number):
f=open('emp.dat','rb')
f1=open('temp.dat','wb')
d={}
a=0
try:
while True:
d=pickle.load(f)
if d['employee_id']!=employee_number:
pickle.dump(d,f1)
print("Record deleted successfully.")
except EOFError:
f.close()
f1.close()
os.remove('emp.dat')
os.rename('temp.dat','emp.dat')
createfile()
x=int(input("Enter id to be deleted :"))
delrec(x)
OUTPUT: