File Handling-Text File
Using write() function program
Q1. Write a function result() to open a file “Student.txt” in write
mode. Store names of the five students along with the marks in English, Maths
and Computer Science in this file.
def result():
fw=open('Student.txt', 'w')
print("To store names of give
students along with the marks in the file.")
for a in range(5):
nm=input("Enter name : ")
eng=int(input("Enter marks in English : "))
maths=int(input("Enter the marks in Maths : "))
comp=int(input("Enter the marks in Computer Science : "))
rec=nm+''+str(eng)+' '+str(maths)+' '+str(comp)+"\n"
fw.write(rec)
fw.close()
#main Program
result()
Output:
=================== RESTART: G:/Data.py ===============
To store names of give students along with the marks in the file.
Enter name : Varun
Enter marks in English : 65
Enter the marks in Maths : 78
Enter the marks in Computer Science : 56
Enter name : Soumya
Enter marks in English : 87
Enter the marks in Maths : 98
Enter the marks in Computer Science : 76
Enter name : Priyanshi
Enter marks in English : 78
Enter the marks in Maths : 89
Enter the marks in Computer Science : 67
Q2. Write a function Multiple() in Python to create a text file
‘Note.txt’ to write few lines into it. If you don’t want more lines then enter
0(zero) to quit the function
def Multiple():
fw=open('Note.txt', 'w')
print("Write a paragraph:")
a=1
while a==1:
line=
input("Write line by line :")
fw.write(line+"\n")
print("Do you want add more line....")
a=int(input("Press 1 to Continue and 0 to Quit "))
fw.close()
#main Program
Multiple()
Q3. 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.upper()=='N':
break
f.close()
#main program
write()
Q4. 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()
Q5. 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("Notes.txt",'a')
sen = input("Enter a sentance :-")
add(sen)
f.close()
Q6. Write a program to add two more employees'
details to the file "emp.txt" already stored in disk.
f = open("emp.txt ",'a')
emno = input("Enter number of Employee :-")
nam = input("Enter a name of Employee :-")
f.write(emno+" , "+nam)
f.close()
Q7. Write a function Contact() in Python to create a text file
“Phone.txt” to write the names of five people along with their contact
numbers.
def Contact():
fw=open("Phone.txt", 'w')
print("To store names of give peiple along with
their contact numbers in the file :")
for a in range(5):
nm=input("Enter name
:")
telnm=input("Enter
contact number : ")
rec=nm+''+telnm+"\n"
fw.write(rec)
fw.close()
#main program
Contact()
Using readline() function program
Q1. Write a function display to open the same file ‘Student.txt’ in
reamodede which will retrieve and display all the records available in the file
“Student.txt”
def display():
fr=open('Student.txt', 'r')
print("To read all the records
from the file. ")
print("Names and Marks in English,
Maths and Computer Science")
while True:
rec=fr.readline()
print(rec,end='')
fw.close()
#main Program
display()
Output:
=================== RESTART: G:/Data.py ===============
To read all the records from the file.
Names and Marks in English, Maths and Computer Science
Varun 65 78 56
Soumya87 98 76
Priyanshi 78 89 67
Avin 76 87 56
Sankalp 98 89 87
Q2. Write a method in Python to read lines from file DIARY.txt and
display those lines which start with alphabet “P”
def display():
file = open("Diary.txt",
"r")
line=file.readline()
count=0
while line:
if
line[0]=='P':
print(line)
line=file.readline()
file.close()
#main program
display()
Q3. Write a method in Python to read lines from a text file MYNOTES.txt
and display those lines which starts with the alphabet ‘K’.
def display():
file = open("MYNOTES.txt",
"r")
line=file.readline()
count=0
while line:
if
line[0]=='P':
print(line)
line=file.readline()
file.close()
#main program
display()
Q4. Write a program that copies a text file “source.txt” onto
“target.txt” barring the lines starting with “@” sign.
def filter(oldfile, newfile):
fin=open(oldfile, "r")
fout=open(newfile, "w")
while True:
text=fin.readline()
if len(text) ==0:
break
if text[0]=='@':
continue
fout.write(text)
fin.close()
fout.close()
filter("source.txt","target.txt")
Q5. Write a function Line() in Python to use the previous text ile
(Notebook.txt) in appropriate mode to retrieve all the lines. Count the number
of lines available in the file and display all the with line number.
def Lines():
fr=open("Name.txt", "r")
print("Display Line
and Line Number : ")
print("Line No.
:","Line")
c=0
line=True
while line:
line=fr.readline()
if
line==" ":
continue
c=c+1
print(c, " ", line, end='')
fr.close()
#main program
Lines()
Using readlines function programs
Q1. Write a user define function in Python that displays the number of
lines starting with ‘H’ in file Para.txt Example if the contains:
Whose woods these are I
think I know.
His house is in the village
though;
He will not see me stopping
here
To watch his woods fill up
with snow.
Then the line count should be 2.
def countH():
f=open("Para.txt",
"r")
lines=0
l=f.readlines()
print(l)
for i in l:
if
i[0]=='H':
lines+=1
print("No. of lines are : ",
lines)
#main program
countH()
Q2. Write a program to search the names and
addresses of persons having age more than 30 in the data list of persons.
f = open("csnip.txt",'r')
data = f.readlines()
for i in data :
age = i.split(",")
if int(age[ 2 ]) >= 30 :
print(age[ : 2 ])
Q3. Write a function in python to count and display the number of lines
starting with alphabet 'A' present in a text file "LINE.Text". eg. The file
“LINE.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.
The function should display the output as 3.
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()
Q4. Write a program to read a file ‘story.txt’ and create another file,
storing an index of story.txt, telling which line of the each word appears in.
if word appears more than once, then index should show al the line numbers
containing the word.
file1 =
open("story.txt","r")
file2 = open("Notes.txt","w")
data = file1.readlines()
for line in data :
words = line.split()
for j in words :
file2.write( j )
file2.write(" = ")
file2.write( "index :-
" + str ( line.index( j ) ) + " line:- " + str(data.index( line)
+1 ) )
file2.write( "\n" )
file1.close()
file2.close()
Q5. Write a program to accept a filename from the user and display all
the lines from the file which contains 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()
Q6. A file contains a list of telephone
numbers in the following form:
Arvind 7258031
Sachin 7259197
The names contain only one word the names and
telephone numbers are separated by white spaces Write program to read a file
and display its contents in two columns.
print("Name\t|\tPhone no. ")
file = open("Note.txt", "r")
lst = file.readlines()
for i in lst :
data = i.split()
print( data[0] ,end = "\t" )
print("|" , end = "\t")
print ( data[1] )
file.close()
Q7. Write a program to count the words "to" and "the" present in a text file "Poem.txt".
Poem.txt Contains :-
This is the Python Website.
We are going to do some Python code
Like a joy on the heart of a sorrow,
The sunset hangs on a cloud;
A golden storm of glittering sheaves,
Of fair and frail and fluttering leaves,
The wild wind blows in a cloud.
Hark to a voice that is calling
To my heart in the voice of the wind:
My heart is weary and sad and alone,
For its dreams like the fluttering leaves have gone,
And why should I stay behind?
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()
Q8. A file “Phone.txt” is a text file which contains few names of the
consumers. Write a function Display() in Python to open the file in an
appropriate mode to retrieve the names. Count and display the names of all the
consumers with the phone numbers whose names start with the letter ‘D’. Assume
that the file already exists in the system.
def Display():
fr=open("Phone.txt", "r")
line=fr.readlines()
print("Names with the Contact Numbers:")
c=0
for a in line:
if a[0]=='D':
print(a, end='')
c=c+1
print("Total number of consumers :", c)
fr.close()
#main priogram
Display()
Q9. Reading a file line by line from the
beginning What if you want to read a file backward? This happens when you need
to read log files. Write a program to read and display content of file from end
to beginning.
f1 = open("Poem.txt",'r')
data = f1.readlines()
content = ""
for i in data :
content += i+"\n"
for i in range (-1 , -len(content),-1):
print(content[ i ],end = "")
f1.close()
Q10. 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()
Q11. Write a function Remove_Lowercase() that
accepts two file names, and copies all lines that do not start with lowercase
letter from the first file into the second file.
def Remove_Lowercase(f1,f2) :
data = f1.readlines()
for i in data :
if i[ 0 ].isupper() :
f2.write(i + "\n")
f1 = open("Poem.txt",'r')
f2 = open("Poem1.txt",'w')
Remove_Lowercase(f1,f2)
f2.close()
Q12. Write a program to display all the
records in a file along with line/record number.
Let us consider content of file be like --
Java, BlueJ, cp
Computer, portal, express
f = open("Notes.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()
Q13. Write a method in Python to write
multiple line of text contents into a text file mylife.txt.
f1 = open("Note.txt", 'r')
f2 = open("myfile.txt", "w")
data = f1.readlines()
for i in data :
f2.write(i)
f2.close()
Q14. 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()
Q15. 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".
Let us consider content of file be like --
Name, Marks
def dispaly(aut):
f =
open("Student.dat", "rb")
try :
while True:
data = pickle.load(f)
if data[1] < 40 :
print( data)
except EOFError:
f.close()
Q16. . Write a function Words() in Python to
read lines from a text file Story.txt. Count and display the number of words
available in the text file.
fr=open('Story.txt')
lines=fr.readlines()
count=0
print(lines)
for i in lines:
count=count+len(i.split())
fr.close()
print("Count words :",
count)
Q17. The file 'City.txt’ stores the names of few
selected cities with the Pincode. Write function Display() to read data and
display only those cities with the Pincode whose first letter is not a vowel.
Sample Output:
New Delhi
700028
Varanasi
110005
Dum
Dum 212011
fr=open('city.txt','r')
lines=fr.readlines()
##print(lines)
for i in lines:
if i[0] not
in 'aeiouAEIOU':
print(i,end='')
fr.close()
Q18. Write a function Vowel() in Python to
read lines from a text file Biography.txt. Count and display the number of
vowels present in the file.
def vowel():
fr=open('Biography.txt','r')
lines=fr.readlines()
##print(lines)
count=0
for i in
lines:
if i[0] in 'aeiouAEIOU':
print(i,end='')
count+=1
fr.close()
print('Count
vowel city : ',count)
#main Program
vowel()
Q19. Write a function Lastline() in Python to
read lines from a text file Paragraph.txt and display the last five lines of
the file on the output screen. Write the main program to call the function.
[Hint: fr =
open("Paragraph.txt","r")
Line= fr.readlines()
print(line[-1]) # displays the
last line of the file]
def LastNlines(fname, N):
file=open(fname)
line=file.readlines()
for i in
(line[-N:]):
print(i, end='')
#main Program
LastNlines('Story.txt',3)
def LastNlines(fname, N):
with open(fname)
as file:
for line in (file.readlines() [-N:]):
print(line, end ='')
#main Program
LastNlines('Story.txt',3)
Q20. A text file
Admission.txt' stores all the names of the students with the admission number
and the stream in which they have taken admission in class XI. The school wants
to keep all the records in different streams viz. Science, Arts and Commerce.
Write a function Separate to create three files as Science.txt, Arts.txt' and
'Commerce txt. Copy all the records of the students accordingly in three files
with the same details.
[Hint: Open three files in
write mode and read the data from the file Admission.txt]
fr=
open("Admission.bxt","r")
fw1=
open("Science.txt","w")
fw2= open("Arts.txt",
"w")
fw3=open("Commerce.txt","w")
..............................................
..........................................
Admission.txt file
Narain 34 Science
Manoj 45 Arts
Sachin 23 Commerce
Deepak 11 Arts
Satyam 22 Science
Arif 12
Commerce
Jai 55
Arts
fr=open('Admission.txt','r')
line=fr.readlines()
print(line)
fs=open('Science.txt','w')
fa=open('Arts.txt','w')
fc=open('Commerce.txt','w')
a=s=c=[]
for i in line:
if 'Arts' in
i:
fa.writelines(i+'\n')
if
'Science' in i:
fs.writelines(i+'\n')
if 'Commerce'
in i:
fc.writelines(i+'\n')
fs.close()
fc.close()
fa.close()
Q21. A file 'Poem.txt' stores a poem
containing few lines. Define a function poem() to read all the lines from the
file and display the poem on the output screen with the heading.
def poem():
fr=open('Poem.txt')
lines=fr.readlines()
for i in lines:
print(i, end='')
#main program
poem()
Q22. The sports department
of a school has purchased few indoor and outdoor games equipments for the students.
Define a function Games_Record() to create a file Games.txt and enter all the
equipments with their details viz. name, price and quantity.
fr=open('Games.txt')
lines=fr.readlines()
for i in lines:
print(i, end='')
#main program
Games_Record()
Using read() function programs
Q1. Write a function countmy() in Python toread the text file
“DATA.txt” and count the number of times “my” occurs in the file. For example, if the file “DATA.txt”
contains- “This is my website. I have displayed my preferences in the CHOUCE
section.”- the countmy() function shoule display the output as : “my occurs 2
times”.
def countmy():
f = open("DATA.txt",
"r")
count=0
x = f.read()
word = x.split()
for i in word:
if
(i=="my"):
count+=1
print("My occures :", count,
" times")
#main program
countmy()
Q2. Write a program to count the number of uppercase 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
print("Number of upper case alphabet : ", count)
file.close()
Q3. Write a program that copies one file to
another. Have the program read the file names from user ?
file1 = input("Enter the name of original file :- ")
file2 = input("Enter the name of New file
:- : ")
old = open( file1 , "r")
new = open( file2, "w")
data = old.read()
new.write( data )
print(" Program run successfully ")
old.close()
new.close()
Q4. The file ‘Name.txt' stores the names of
all the students of class XII with admission number. Write a function Count()
to read the records from the file. Count and display all the uppercase and
lowercase letters available in the file.
[Hint: use split()]
def count():
fr=open('Science.txt')
lines=fr.read()
countU=countL=0
for i in lines:
if
i.isupper():
countU+=1
if
i.islower():
countL+=1
fr.close()
print("Upper Count
letters :", countU)
print("Lower Count
letters :", countL)
# main program
count()