File handling programs
File handling programs
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.
filel1= open("sample.txt","r") file1 = open("portal.txt","r")
file2 = open("New.txt","w") file2 = open("Express.txt","w")
lst= file1.readlines () lst = file1.readlines()
for i in lst:
for i in lst :
word = i.split()
file2.write("".join(word) ) word = i.split()
file2.write("\n") for j in word :
print("Program has successfully run") file2.write( j + "")
file2.close() file2.write("\n")
file1.close() print("Program has successfully run")
file2.close()
file1.close()
2. 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".
to_no = 0
the_no = 0
file = open("Poem.txt", "r")
lst = file.readlines()
for i in lst :
word = i.split()
for j in word :
if j == "to" or j == "To" :
to_no += 1
elif j == "the" or j == "The" :
the_no += 1
print("Number 'to' : " , to_no)
print("Number 'the' : " , the_no)
file.close()
def AMCount( ):
f = open("STORY.txt", "r",)
data = f.read()
count_a = 0
count_m = 0
for i in data :
if i == "a" or i == "A":
count_a += 1
elif i == "m" or i == "M":
count_m += 1
print("A or a :", count_a )
print("M or m:", count_m)
AMCount()
file1 = input("Enter the name of file which you want to append : ")
file2 = input("Enter the name of original file : ")
old = open( file2 , "r" )
new = open( file1 , "a" )
data = old.read()
new.write( "\n" + data)
print("Program run successfully ")
old.close()
new.close()
display_lines("MYNOTES.TXT")
def DISPLAYWORDS() :
file = open("story.txt", "r")
lst = file.readlines()
for i in lst :
word = i.split()
for j in word :
if len( j ) < 4 :
print( j )
file.close()
print("Word with length smaller than 3 :- \n")
DISPLAYWORDS()
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.
upper = open("UPPER.txt","w")
lower = open("LOWER.txt" , "w" )
other = open ("OTHER.txt" , "w")
while True :
user = input("Enter a charracter (for exit enter quit ): ")
if user == "quit" or user == "Quit" :
break
elif user.isupper() :
upper.write( user + "" )
elif user.islower( ) :
lower.write( user + "" )
else :
other.write( user + "" )
upper.close()
lower.close()
other.close()
print("Thankyou")
count = 0
file = open("LINES.txt","r")
lst = file.readlines()
for i in lst :
if i[ 0 ] == "A" :
print(i)
count += 1
print()
print("So for number of sentences started with A : ",count)
file.close()
file = open("pathwalla.txt","r")
data = file.read()
for i in range( len( data ) ):
if data [ i ] == "$" :
break
print( "Total number of characters up to the first $ before = ",i )
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.
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)...")
import pickle
file = open("staff.dat", "rb")
found = 0
try :
while True :
staff = pickle.load(file)
if staff [ "Staff Code" ] == 'S0105':
print(staff)
found=1
except EOFError :
if found == 0:
print("Not found !!!")
file.close()
import pickle
file = open("COMPANY.DAT","rb")
found = 0
try :
while True :
Company = pickle.load(file)
if Company [ "CompID" ] == '1005':
print(Company)
found=1
except EOFError :
if found == 0:
print("Not found !!!") a
file.close()
import pickle
def search() :
file = open("TRAIN.DAT","rb")
found = 0
try :
while True :
Train = pickle.load(file)
if Train [ "To" ] == 'Delhi':
print(Train)
found=1
except EOFError :
if found == 0:
print("Not found !!!")
file.close()
search()
import pickle
def CreateFile():
f = open("Book.dat", "wb")
while True :
num = int(input("Enter Book Number :- "))
name = input ("Enter Book Name :- ")
aut = input("Enter Author :- ")
pri = float(input("Enter Price of Book :- "))
lst= [ num, name, aut, pri]
pickle.dump( lst, f)
choice = input("For exit (Enter exit):- ")
print()
if choice == "exit" or choice == "Exit":
print("Thank you")
print()
break
f.close()
def CoutRec(aut):
f = open("Book.dat", "rb")
count = 0
try :
while True:
data = pickle.load(f)
if data[2] == aut :
count += 1
except EOFError:
f.close()
print("Number of Book with Author name", aut , "=", count)
CreateFile()
print("For Searching -")
aut = input("Enter Author :- ")
CoutRec(aut)
21. Write a Python program to read a given CSV file having tab
delimiter.
import csv
file = open( "Pathwalla.csv","r" )
data = csv.reader(file, delimiter = "\t")
for i in data :
print(i)
file.close()
22. Write a Python program to write a nested Python list to a csv file
in one go. After writing the CSV read the CSV file and display the
content.
import csv
file = open( "Portal.csv","w",newline="" )
lst = eval(input("Enter a nested list :- "))
path_write = csv.writer( file)
path_write.writerows( lst )
file.close()
print()
print("Content of Portal.csv :")
print()
file = open( "Portal.csv","r" )
data = csv.reader(file )
for i in data :
print(i)
file.close()
23. Write a function that reads a csv file and creates another csv file
with the same content, but with a different delimiter.
import csv
def Pathwalla( file1 ):
file2 = open( "Portalexpress.csv","w",newline="" )
portal_write = csv.writer( file2 , delimiter = "|")
data = csv.reader(file1)
for i in data :
if i[0][:5] != "check" :
portal_write.writerow( i )
file2.close()
file1 = open( "Pathwalla.csv","r" )
Pathwalla( file1 )
print ("Thank You !!")
24. Write a program to read the records of this csv file and display
them.
import csv
with open("compresult.csv", "r") as fh :
creader = csv.reader(fh)
for rec in creader:
print(rec)
import csv
fh = open("Student.csv", " w" )
stuwriter = csv.writer(fh)
stuwriter.writerow( ['Rollno', 'Name', 'Marks'] )
for i in range(5):
print("Student record", (i+1))
rollno = int(input("Enter rollno:"))
name = input("Enter name:") marks = float(input("Enter marks:"))
sturec = [rollno, name, marks]
stuwriter.writerow(sturec)
fh.close()
import csv
fh = open("compresult.csv", "w")
cwriter = csv.writer(fh)
compdata = [
['Name', 'Points', 'Rank'],
'Shradha', 4500, 23],
['Nishchay', 4800, 31],
['Ali', 4500, 25],
['Adi', 5100, 14] ]
cwriter.writerows(compdata)
fh.close()
27. Aman is a Python programmer. He has written a code and
created a binary file record dat with employee id, ename and salary.
The file contains 10 records.
He now has to update a record based on the employee id entered by
the user and update the salary. The updated record is then to be
written in the file temp.dat. The records which are not to be
updated also have to be written to the file temp.dat. If the
employee id is not found, an appropriate message should to be
displayed. As
a Python expert, help him to complete the following code based on
the requirement given above:
import Pickle
def update_data():
rec ={ }
fin =open( "record.dat" ,"rb")
fout=open("temp.dat", " w")
found=False
eid = int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=pickle.load(fin)
if rec["Employee id"] == eid :
found = True
rec["Salary"] = int(input("Enter new salary :: "))
pickle. dump(rec, fout)
else:
pickle.dump(rec, fout)
except:
break
if found == True:
print("The salary of employee id ", eid," has been
updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
import pickle
def CountRec():
fobj = open("STUDENT.DAT","rb")
num=0
try :
while True:
rec = pickle.load(fobj)
if rec[2] >75:
print(rec[0], rec[1], rec[2], sep= "\t")
num = num + 1
except:
fobj.close()
return num
import pickle
emp={}
found=False
fin =open( empl.dat', 'rb+')
try:
while True :
emp =pickle. load(fin)
if emp['Empno"] == 1251:
emp['Salary'] = emp['Salary'] + 2000
pickle.dump(emp, fin)
print(emp)
found=True
except EOFError:
if found == False:
print("Sorry, no matching record found.")
else:
print("Record(s) successfully updated.")
fin.close()
30. What is the advantage of using a csv file for permanent storage?
Write a Program in Python that defines and calls the following user
defined functions:
31. 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 :
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.
def search():
found = False
f1= open('furdata.csv', 'a')
reader = csv.reader(f1)
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()
32. Write a function that reads a csv file and creates another csv file
with the same content except the lines beginning with 'check'.
import csv
def filter(input_file, output_file):
fin = open(input_file, 'r',)
fout= open(output_file, 'w',)
reader = csv.reader(fin)
writer = csv.writer(fout)
filter('input.csv', 'output.csv')