25 Programs -Data file Handling
25 Programs -Data file Handling
infile.close()
outfile.close()
2. 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.
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
file.close()
5. Write a program to count the number of upper- case alphabets present in a text file
"Article.txt".
count = 0
file = open("Article.txt","r")
sen = file.read()
for i in range ( len(sen) ) :
if sen[ i ].isupper() :
count += 1
6. write a program that copies one file to another. Have the program read the file names from
user.
file = input("Enter file name")
def file_check:
f = open(file + '.txt','r')
data = f.read()
f.close()
data = data.split('\n')
file = []
file_check.append(list(row))
return file_check
7. Write a program that appends the contents of one file to another. Have the program take
the filenames from the user.
file1 = input("Enter the name of file which you want to append : ")
file2 = input("Enter the name of original file : ")
data = old.read()
new.write( "\n" + data)
old.close()
new.close()
8. 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")
9. Write a program to search the names and addresses of persons having age more than 30 in
the data list of persons.
f = open("Pathwala.txt",'r')
data = f.readlines()
for i in data :
age = i.split(",")
if int(age[ 2 ]) >= 30 :
print(age[ : 2 ])
10. 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.
f1 = open(‘LINES.txt’, ‘r’)
l = f1.readlines() # creates a list of all the lines in the file
print(‘Number of lines starting with A in the file LINES.txt is’, func(l))
11. Write the file mode that will be used for opening the following files. Also, write the
Python statements to open the following files:
Answer :-
12. Why is it advised to close a file after we are done with the read and write operations?
What will happen if we do not close it? Will some error message be flashed?
Answer :-
Closing the file releases the resources. On a large system running many process you can use
up all of the resources to keep track of open files. This may prevent any process from opening
another file. When the process ends or crashes the OS is supposed to clean up for you.
13. What is the difference between the following set of statements (a) and (b):
a) P = open("practice.txt","r")
P.read(10)
b) with open("practice.txt", "r") as P:
x = P.read()
Answer :-
In part "a" file P will read 10 characters but will not print anythings while in part "b" it will
read whole character present in practice file and store in variale "x".
14. Write a program to accept string/sentences from the user till the user enters "END" to.
Save the data in a text file and then display only those sentences which begin with an
uppercase alphabet.
Answer :-
f = open("Pathwalla.txt","w")
while True :
sen = input("Enter something ( for quit enter END ) :-")
if sen == "END" :
break
else :
f.write(sen + "\n")
f.close()
print()
print("The Lines started with Capital letters are :-")
f = open("Pathwalla.txt","r")
15. Write a function to insert a sentence in a text file, assuming that text file is very big and
can't fit in computer's memory.
def add(sen) :
f.write("\n"+ sen)
f = open("path.txt",'a')
sen = input("Enter a sentance :-")
add(sen)
f.close()
16. Write a program to read a file 'Story.txt' and create another file, storing an index of
Story.txt, telling which line of the file each word appears in. If word appears more than once,
then index should show all the line numbers containing the word.
Ans:
file1 = open("story.txt","r")
file2 = open("Path walla.txt","w")
data = file1.readlines()
file1.close()
file2.close()
17. Write a program to accept a filename from the user and display all the lines from the file
which contain Python comment character '#'.
user = input("Enter file name :-")
f = open(user + ".txt",'r')
data = f.readlines()
for i in data :
if "#" in i :
print(i)
f.close()
18. Write a Python program to display the size of a file after removing EOL characters,
leading and trailing white spaces and blank lines.
f1 = open("path.txt",'r')
data = f1.readlines()
content = ""
for i in data :
for j in i :
if j.isalnum():
content += j
print("file size:-",len(content),"bits")
f1.close()
19. Write a program to display all the records in a file along with line/record number.
f = open("pathwalla.txt",'r')
data = f.readlines()
for i in range (len(data)) :
line = data[ i ].split(",")
print("Line number =",i+1)
for j in range (len(line)):
print("Record number = ",j+1,end=" , ")
print(line[ j ])
f.close()
20. Write a method in Python to write multiple lines of text contents into a text file
daynote.txt line.
def write () :
f = open ("daynote.txt", 'w')
while True:
line = input ("Enter line:")
f.write (line)
choice = input("Are there more lines (Y/N):")
if choice == 'N':
break
f.close()
21. Write a method in Python to read the content from a text file DIARY.TXT line by line
and display the same on the screen.
f1 = open("DIARY.TXT ",'r')
data = f1.readlines()
for i in data :
print(i)
f1.close()
22. Create a CSV file "Groceries" to store information of different items existing in a shop.
The information is to be stored w.r.t. each item code, name, price, qty. Write a program to
accept the data from user and store it permanently in CSV file.
import csv
data = []
while True :
item_code = input("Enter item code :-")
name = input("Enter name :-")
price = input("Enter price :-")
qty = input("Enter Quantity :-")
data += [[ item_code, name, price, qty ]]
user = input("Do you want to enter more data (yes/no)")
if user == "No" or user == "no" :
break
with open("Groceries.csv","w",newline="") as f :
csv_w = csv.writer(f,delimiter=',')
csv_w.writerows(data)
23. Anant has been asked to display all the students who have scored less than 40 for
Remedial Classes, Write a user-defined function to display all those students who have
scored less than 40 from the binary file "Student.dat".
f = open("pathwala.txt",'r')
data = f.readlines()
for i in data :
line = i.split(',')
if int(line[ 1 ])< 40 :
print(i)
f.close()
24. Consider a binary file Employee.dat containing details such as empno:ename:salary
(separator ‘ :’). Write a python function to display details of those employees who are earning
between 20000 and 40000.(both values inclusive).