You are on page 1of 3

File Programs

Problem 1:

Write a program to read a file and count the number of occurrences of alphabets. Display the result in
sorted order of the occurrences

Program 1:

alphabet_dict = {}
for i in range (97 , 123 ):
alphabet_dict[ chr( i ) ] = 0
for i in range (65 , 91):
alphabet_dict[ chr( i ) ] = 0
fd = open('pangrams.txt','r')
ch = fd.read(1)
while ch:
if str.isalpha(ch):
alphabet_dict[ch] = alphabet_dict[ch] + 1
ch = fd.read(1)
alpha_nze_dict = { k : v for (k , v ) in
alphabet_dict.items() if v != 0}
l = sorted(alpha_nze_dict,key = alpha_nze_dict.__getitem__ )
for key in l:
print ( key , '=' , alpha_nze_dict[ key ] )

Problem 2:
Write a program to merge two file into the third file
Program 2:
fd1 = open('numlist1.txt','r')
fd2 = open('numlist2.txt','r')
fd3 = open('merlist.txt','w')

line1 = fd1.readline().strip()#read first line from fd1


line2 = fd2.readline().strip()#read first line from fd2
while ( line1 and line2 ): # iterate till any one file reaches
#eof
num1 = int(line1)
num2 = int(line2)
if num1 < num2 :
fd3.write(str(num1)+'\n')# write first file content
#into fd2
line1 = fd1.readline().strip()# read nextline from fd1
else:
fd3.write(str(num2)+'\n') )# write first file content
#into fd2
line2 = fd2.readline().strip()()#read nxtline from fd2

1
if line1: #checks if fd2 is empty
line = line1
fd = fd1
fd2.close()
else: # checks if fd1 is empty
line = line2
fd = fd2
fd1.close()

while(line): #write remaining contents of


#nonempty file in fd3
fd3.write(str(line)+'\n')
line = fd.readline().strip()

fd3.close()

Problem 3:
Write a program to write contents into an excel file
fd = open('sample.csv','r')

s = fd.readline()

con = 1

while con == 1:
s = input() #read inpu with comma seperation
# 98,67,77,89,90,89
fd.write( s +'\n')
con = int(input())
fd.close()

Problem 4:
Write a program to read contents from an excel file line by line
fd = open('sample.csv','r')
s = fd.readline()

while( s ): # print line by line


l = s.split(',')

print (l)
s = fd.readline()

fd.close()

2
Problem 4:
Write a program to read contents from an excel file all lines n storing the whole file as list.
fd = open('sample.csv','r')
l = fd.readlines()
print ( l )
fd.close()

Problem 5:
Write a program to read student mark details from excel file n find max min and average in
all subjects as dictionary

fd = open('m.csv','r')
sub_list = [ [ ] for i in range(6) ]
#print (sub_list)
l = fd.readlines()
print ( l )
for dataString in l:
dl = dataString.split(',')
for i in range ( 6):
sub_list[ i ].append(int(dl[ i ]))

#print (sub_list)
list_subjects = [ 'English','Maths','Science','SST','VE','CS' ]

max_dict = { list_subjects[ i ] : max(sub_list[ i ]) for i in range( 6 ) }


min_dict = { list_subjects[ i ] : min(sub_list[ i ]) for i in range( 6 ) }
ave_dict = { list_subjects[ i ] : sum(sub_list[ i ])/len(sub_list[ i ])
for i in range( 6 ) }
print ( max_dict )
print ( min_dict )
print ( ave_dict )

fd.close()

You might also like