You are on page 1of 15

FILE HANDLING PROGRAMS

TEXT FILE
BINARY FILE
CSV FILE

1. Write a python script to read the contents of a File character by character and display them?
def file_read1():
with open("abc.txt") as f:
while True:
c=f.read(1)
if not c:
#print("end of file")
break
print(c,end='')
#function calling
file_read1()

2. write a (python script) function named count_len() to read the contents of the file “abc.txt”
and print its length.
def count_len():
le=0
with open("abc.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
le=le+1
print("length of file ",le)
#function calling
count_len()

3. write a (python script) function named count_lower() to read the contents of the file “story.txt”.
Further count and print total lower case alphabets in the file
def count_lower():
lo=0
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if(c>='a' and c<='z'):
lo=lo+1
print("total lower case alphabets ",lo)
function calling
count_lower()

1|Pa ge
4. write a (python script) function named count_upper() to read the contents of the file “story.txt”.
Further count and print total upper case alphabets in the file.
def count_upper():
lo=0
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if(c>='A' and c<='Z'):
lo=lo+1
print("total upper case alphabets ",lo)
function calling
count_upper()

5. write a (python script) function named count_digit() to read the contents of the file “story.txt”.
Further, count and print total digit in the file
def count_digit():
d=0
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if(c>='0' and c<='9'):
d=d+1
print("total digits ",d)
#function calling
count_digit()

6. write a (python script) function named count_vowels() to read the contents of the file “story.txt”.
Further count and print total vowels in the file.
def count_vowels():
d=0
vowels="aeiouAEIOU"
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if(c in vowels):
d=d+1
print("total digits ",d)
#function calling
2|Pa ge
count_vowels()

7. write a (python script) function named count_consonants() to read the contents of the file
“story.txt”. Further, count and print total consonants in the file.
def count_consonants():
c1=0
vowels="aeiouAEIOU"
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if((c>='A' and c<='Z') or(c>='a' and c<='z')):
if not (c in vowels):
c1=c1+1
print("total consonants ",c1)
#function calling
count_consonants()

8. write a (python script) function named count() to read the contents of the file “story.txt”. Further
count and print the following:
#total length
#total alphabets
#total vowels
#total conbsonants
#total non alpha chars
def count():
d=0
le=0
c1=0
c2=0
a=0
vowels="aeiouAEIOU"
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
le=le+1
if((c>='A' and c<='Z') or(c>='a' and c<='z')):
a=a+1
if (c in vowels):
d=d+1
else:
c1=c1+1
c2=c2+1
3|Pa ge
print("total vowels ",d)
print("total consonants ",c1)
print("total alphabets ",a)
print("total chars which are not alphabets ",c2)
print("length = ",le)
#function calling
count()

9. write a (python script) function named count_spaces() to read the contents of the file “story.txt”.
Further count and print total spaces in the file.
def count_space():
d=0
space=" "
with open("story.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if(c in space):
d=d+1
print("total spaces ",d)
#function calling
count_space()

10. write a (python script) function named read_words() to read the contents of the file “abc.txt”
word by word and display the contents.

Method:1

def read_words():
with open("file1.txt") as f:
while True:
d=f.readline()
if not d:
break
for word in d.split():
#for word in line.split():
print(word)
#function calling
read_words()

Method:2

def read_words():
with open("file1.txt") as f:
while True:
d=f.readline()
4|Pa ge
if not d:
break
for word in d.split():
#for word in line.split():
print(word)
#function calling
read_words()

11. write a (python script) function named count_words() to read the contents of the file “abc.txt”
word by word and display the contents. and also display total words in the file

Method 1

def read_words():
c=0
with open("file1.txt") as f:
while True:
d=f.readline()
if not d:
break
for word in d.split():
#for word in line.split():
print(word)
c=c+1
print('no of words=',c)
#function calling
read_words()

Method 2

def count_words():
w=0
with open("file1.txt") as f:
for line in f:
for word in line.split():
print(word)
w=w+1
print("total words ",w)
#function calling
count_words()

12. write a (python script) function named count_words() to read the contents of the file “abc.txt”
word by word and display the contents. and also display total number of words starting with “a”
or “A” in the file.
def count_words():
w=0
with open("abc.txt") as f:
for line in f:
5|Pa ge
for word in line.split():
if(word[0]=="a" or word[0]=="A"):
print(word)
w=w+1
print("total words starting with 'a' are ",w)
#function calling
count_words()

13. write a (python script) function named count_words() to read the contents of the file “abc.txt”
word by word and display the contents. and also display total number of words starting with
tarting with vowels “a”,”e”,”i”,”o”,”u” or “A” ,”E”,”I”,”O”,”U”

def count_words():
w=0
vowels="aeiouAEIOU"
with open("abc.txt") as f:
for line in f:
for word in line.split():
if(word[0] in vowels):
print(word)
w=w+1
print("total words starting with vowels are ",w)
#function calling
count_words()

14. write a (python script) function named count_words() to read the contents of the file “abc.txt”
word by word and display the contents. and also display total number of words ending with “t” or
“T” in the file. and also display length of each word
def count_words():
w=0
with open("abc.txt") as f:
for line in f:
for word in line.split():
i=len(word)
if(word[i-1]=="T" or word[i-1]=="t"):
print(word," ",len(word))
w=w+1
print("total words ending with 't' are ",w)
function calling
count_words()

15. write a (python script) function named count_words() to read the contents of the file “abc.txt”
word by word and display the contents. and also display total number of words ending with
vowels and also display length of each word.
def count_words():
w=0
vowels='aeiouAEIOU'
with open("abc.txt") as f:
6|Pa ge
for line in f:
for word in line.split():
i=len(word)
if(word[i-1]in vowels):
print(word," ",len(word))
w=w+1
print("total words ending with vowels are ",w)
function calling
count_words()

16. write a (python script) function named count_words() to read the contents of the file “abc.txt”
word by word. Check and print total “the” present in the file
def count_words():
w=0
with open("abc1.txt") as f:
for line in f:
for word in line.split():
n=word.lower()
if(n=="the"):
w=w+1
print("total words 'the' present: ",w)
function calling
count_words()

17. write a (python script) function named count_words() to read the contents of the file “abc.txt”
word by word. Check and print total “this” present in the file.
def count_words():
w=0
with open("abc1.txt") as f:
for line in f:
for word in line.split():
n=word.lower()
if(n=="this"):
w=w+1
print("total words 'this' present: ",w)
function calling
count_words()

18. Python Program to read a file “story.txt” line by line and display the contents
filepath = 'story.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
print(cnt," ",line,end='')
line = fp.readline()
cnt += 1

7|Pa ge
19. Python Program to read a file “story.txt” line by line and display the
contents. Further count and print total lines in the file
filepath = 'story.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 0
while line:
cnt += 1
print(cnt," ",line,end='')
line = fp.readline()
print("Total lines in file ",cnt)

20. Python Program to read a file “story.txt” line by line and display the
contents. count and print total lines starting with “A” or “a” in the file
filepath = 'story.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
if(line[0]=='a' or line[0]=='A'):
#print(line)
print(cnt," ",line,end='')
cnt=cnt+1
line = fp.readline()

21. Python Program to read a file “story.txt” line by line and display the
contents. count and print total lines starting with vowels (A,a,E,e,I,i,O,o,U,u) in the file
filepath = 'story.txt'
vowels="AEIOUaeiou"
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
if(line[0] in vowels):
#print(line)
print(cnt," ",line,end='')
cnt=cnt+1
line = fp.readline()

22. Python Program to read a file “story.txt” line by line and display the
contents. count and print total lines not starting with “A” or “a” in the file
filepath = 'story.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
if not (line[0]=='a' or line[0]=='A'):
#print(line)
8|Pa ge
print(cnt," ",line,end='')
cnt=cnt+1
line = fp.readline()

23. Python Program to read a file “story.txt” line by line and display the
contents. count and print total lines not starting with vowels (A,a,E,e,I,i,O,o,U,u) in the file
filepath = 'story.txt'
vowels="AEIOUaeiou"
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
if not(line[0] in vowels):
#print(line)
print(cnt," ",line,end='')
cnt=cnt+1
line = fp.readline()

24. #Python Program to read a file “data.txt” line by line and display the
contents. count and print total words in each line.
def count_words():
with open("data.txt") as f:
i=0
for line in f:
i=i+1
w=0
for word in line.split():
print(word)
w=w+1

print("Line ",i," has total words ",w)


#function calling
count_words()

25. #Program to Add record in a Binary File


Points
1. if the file does not exist the create a binary file
2. if the file exits then open the file in append mode
3. Take input for roll, name and per.
4. store them in a variable rec
5. write the record in the binary file using pickle.dump()
6. close the file

import pickle
import os
#function definition
def add_record():
try:
9|Pa ge
if os.path.isfile("stud"):
f=open("stud","ab")
else:
f=open("stud","wb")
roll=int(input("Enter roll no "))
name=input("Enter name ")
name=name.upper()
per=float(input("Enter per "))
rec=[roll,name,per]
pickle.dump(rec,f)
print("Record added in file")
except EOFError:
f.close()
#function calling
add_record()

26. #program to display all the records from binary file


1. open the binary file in read mode
2. if file does not exist then an error will be displayed
4. using a while loop read a binary file
3. read a record from binary file using pickle.load()
4. display the record
5. When EOF is reached close the file.

import pickle
#function definition
def std_dispall():
try:
f=open("stud","rb")
while True:
rec=pickle.load(f)
print(rec)

except EOFError:
f.close()
except IOError:
print("Unable to open the file")

#function calling
std_dispall()

27. #Program to display all the records from binary file (2nd Method)
import pickle
#function definition
def std_dispall_1():
try:
f=open("stud","rb")
print("Roll","Name","Per")
10 | P a g e
while True:
rec=pickle.load(f)
print(rec[0],rec[1],rec[2])

except EOFError:
f.close()
except IOError:
print("Unable to open the file")

#function calling
std_dispall_1()

28. Program to Search a record from binary file using roll number
1. open the binary file in read mode
2. if file does not exist then an error will be displayed
3. Take input for the roll number to search
4. using a while loop read a binary file
5. read a record from binary file using pickle.load()
6. compare the roll number of record read from the file
with the roll number to search
7. if roll number matches then display the record
8. if roll number does not match with any of the records
then display a message “record not found”
5. When EOF is reached close the file.

pickle
import os

#function definition
def search_roll():
try:
z=0
tr=int(input("Enter roll no to search "))
f=open("stud","rb")
print("Roll","Name","Per")
while True:
rec=pickle.load(f)
if rec[0]==tr:
z=1
print(rec[0],rec[1],rec[2])

except EOFError:
f.close()
if z==0:
print("Record not found")
except IOError:
print("Unable to open the file")

11 | P a g e
#function calling
search_roll()

29. #Program to Search a record from binary file using Name


1. open the binary file in read mode
2. if file does not exist then an error will be displayed
3. Take input for the name to search
4. using a while loop read a binary file
5. read a record from binary file using pickle.load()
6. compare the name of record read from the file
with the name to search
7. if name matches then display the record
8. if name does not match with any of the records
then display a message “record not found”
5. When EOF is reached close the file.

import pickle
import os

#function definition
def search_name():
try:
z=0
tn=input("Enter Name to search ")
tn=tn.upper()
f=open("stud","rb")
print("Roll","Name","Per")
while True:
rec=pickle.load(f)
if rec[1]==tn:
z=1
print(rec[0],rec[1],rec[2])

except EOFError:
f.close()
if z==0:
print("Record not found")
except IOError:
print("Unable to open the file")

#function calling
search_name()

30. #Program to Delete a record from binary file using roll number
1. open the binary file in read mode and open a “temp” file in write mode
2. if file does not exist then an error will be displayed
3. Take input for the roll number to delete
4. using a while loop read a binary file
12 | P a g e
5. read a record from binary file using pickle.load()
6. compare the roll number of record read from the file with the roll number to search
7. if roll number matches then display the record
8. if roll number does not match with current record being traversed then write the record in the “temp”
file.
9. When EOF is reached close both the files.
10. if record is found then after the files have been close remove the source file and rename the “temp”
file with the name of source file

import pickle
import os

#function definition
def delete_roll():
try:
z=0
tr=int(input("Enter roll no to delete "))
f=open("stud","rb")
tf=open("temp","wb")
print("Roll","Name","Per")
while True:
rec=pickle.load(f)
if rec[0]==tr:
z=1
print(rec[0],rec[1],rec[2])
else:
pickle.dump(rec,tf)

except EOFError:
f.close()
tf.close()
if z==0:
print("Record not found")
else:
os.remove("stud")
os.rename("temp","stud")

except IOError:
print("Unable to open the file")

#function calling
delete_roll()

31. #Program to Update a record from binary file using roll number
1. open the binary file in read mode and open a “temp” file in write mode
2. if file does not exist then an error will be displayed
3. Take input for the roll number to delete
4. using a while loop read a binary file
13 | P a g e
5. read a record from binary file using pickle.load()
6. compare the roll number of record read from the file with the roll number to search
7. if roll number matches then display the record and take input for new data
8. if roll number does not match with current record being traversed then write the record in the “temp”
file.
9. When EOF is reached close both the files.
10. if record is found then after the files have been close remove the source file and rename the “temp”
file with the name of source file.

import pickle
import os

#function definition
def update_roll():
try:
z=0
tr=int(input("Enter roll no to update "))
f=open("stud","rb")
tf=open("temp","wb")
print("Roll","Name","Per")
while True:
rec=pickle.load(f)
if rec[0]==tr:
z=1
print("Old Record")
print(rec[0],rec[1],rec[2])
print("Enter new data ")
roll=int(input("Enter roll no "))
name=input("Enter name ")
name=name.upper()
per=float(input("Enter per "))
rec=[roll,name,per]
pickle.dump(rec,tf)

except EOFError:
f.close()
tf.close()
if z==0:
print("Record not found")
else:
os.remove("stud")
os.rename("temp","stud")

except IOError:
print("Unable to open the file")

#function calling
14 | P a g e
update_roll()

32. #Python program to create a CSV file named “employee.csv”, to store employee details like
empno,Name and salary of employees.
#writing records in csv file
import csv
f=open('employee.csv','w',newline='')
empwriter=csv.writer(f)
empwriter.writerow(['Empno','Name','Salary']) # write header row
emprec= [
['1001', 'Amit', '45000'],
['1002', 'Sagar', '19800'],
['1003', 'Aditi', '29855'],
['1004', 'Sansar', '86790'],
['1005', 'Pramod', '88000'],
]
empwriter.writerows(emprec)
f.close()

33. Python program read the contents of CSV file named “employee.csv”, and display Empno,Name
and Salary of employees.
# method 1
import csv
with open("employee.csv","r",newline='') as fh:
empreader=csv.reader(fh)
for rec in empreader:
print(rec)
#method 2
with open("employee.csv","r",newline='') as fh:
empreader=csv.reader(fh)
for rec in empreader:
for i in rec:
print(i,end=' ')
print('\n')

15 | P a g e

You might also like