FILE HANDLING (NOTES AND IMPORTANT QUESTIONS OF .
TXT FILE
There are two types of files that can be handled in python, normal text files and
binary files (written in binary language, 0s, and 1s).
• Text files: In this type of file, Each line of text is terminated with a special
character called EOL (End of Line), which is the new line character (‘\n’) in
python by default.
• Binary files: In this type of file, there is no terminator for a line, and the data is
stored after converting it into machine-understandable binary language.
There are 6 access modes in python.
1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the
beginning of the file. If the file does not exists, raises the I/O error. This is also
the default mode in which a file is opened.
2. Read and Write (‘r+’): Open the file for reading and writing. The handle is
positioned at the beginning of the file. Raises I/O error if the file does not exist.
3. Write Only (‘w’) : Open the file for writing. For the existing files, the data is
truncated and over-written. The handle is positioned at the beginning of the file.
Creates the file if the file does not exist.
4. Write and Read (‘w+’) : Open the file for reading and writing. For an existing
file, data is truncated and over-written. The handle is positioned at the beginning
of the file.
5. Append Only (‘a’): Open the file for writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The data being written will
be inserted at the end, after the existing data.
6. Append and Read (‘a+’) : Open the file for reading and writing. The file is
created if it does not exist. The handle is positioned at the end of the file. The
data being written will be inserted at the end, after the existing data.
Opening a File
It is done using the open() function. No module is required to be imported for this
function.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, the full
address of the file should be written in place of the filename. Note: The r is placed
before the filename to prevent the characters in the filename string to be treated as
special characters. For example, if there is \temp in the file address, then \t is treated
as the tab character, and an error is raised of invalid address. The r makes the string
raw, that is, it tells that the string is without any special characters. The r can be
ignored if the file is in the same directory and the address is not being placed.
Eg f=open(“trial.txt”, ‘r+’)
1 AG NOTES
close() function closes the file and frees the memory space acquired by that file. It
is used at the time when the file is no longer needed or if it is to be opened in a
different file mode. File_object.close()
write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
writelines() : For a list of string elements, each string is inserted in the text
file.Used to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Reading from a file
There are three ways to read data from a text file.
read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified,
reads the entire file.
File_object.read([n])
readline() : Reads a line of the file and returns in form of a string. For specified n,
reads at most n bytes. However, does not reads more than one line, even if n
exceeds the length of the line.
File_object.readline([n])
readlines() : Reads all the lines and return them as each line a string element in a
list.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes
Split()
After reading the data, the split() method is used to split the text into words. The
split() method by default separates text using whitespace.
Eg
f=open(‘trial.txt’, ‘r’)
line=f.read()
word=line.split()
Text File – Exam based questions
2 AG NOTES
Write a function in python to count the number Write a user defined function countwords() to
lines in a text file ‘Country.txt’ which is starting display the total number of words present in thefile
with an alphabet ‘W’ or ‘H’. from a text file “Quotes.Txt”.
def count_W_H():
f = open (“Country.txt”, “r”) def countwords():
NW,NH = 0,0 s = open("Quotes.txt","r")
r = f.readlines() f = s.read()
for x in r: z = f.split ()
if x[0]== “W” or x[0]== “w”: print ("Total number of words:", len(z))
NW=NW+1 countwords()
elif x== “H” or x== “h”:
NH=NH+1
f.close()
print (“W or w :”, NW)
print (“H or h :”, NH)
count_W_H()
Write a function DISPLAYWORDS( ) in python to Write a function COUNT_AND( ) in Python to readthe
display the count of words starting with “t” or “T” text file “STORY.TXT” and count the number of times
in a text file ‘STORY.TXT’. “AND” occurs in the file. (include AND/and/And in
def DISPLAYWORDS( ): the counting)
count=0 def COUNT_AND( ):
file=open(‘STORY.TXT','r') count=0
line = file.read() file=open(‘STORY.TXT','r')
word = line.split() line = file.read()
for w in word: word = line.split()for
if w[0] ==’t’ or w[0]==’T’: w in word:
count=count+1 if w.upper() ==’AND’:
print(count) count=count+1
file.close() print(count)
DISPLAYWORDS() file.close()
COUNT_AND()
Write a function to display those lines which start Write a function that counts and display the number
with the letter “G” from the text file of 5 letter words in a text file “Sample.txt
“MyNotes.txt”
def count_lines( ): def count_words( ):
c=0 c=0
f = open("MyNotes.txt") f = open("Sample.txt")
line = f.readlines() line = f.read()
for w in line: word = line.split()
if w[0] == 'G': for w in word:
print(w) if len(w) == 5:c
f.close() += 1
count_lines( ) print(c)
count_words( )
3 AG NOTES
Write a function in python to read lines from file Write a function COUNT() in Python to read contents
“POEM.txt” and display all those words, which from file “REPEATED.TXT”, to count anddisplay the
has two characters in it. occurrence of the word “father” or “mother”.
def TwoCharWord(): def COUNT():
f = open('poem.txt') f = open('REPEATED.txt')
count = 0 count = 0
for line in f: for line in f:
words = line.split() words = line.split()
for w in words: for w in words:
if len(w)==2: if w.lower()==’father’ or w.lower()=='mother':
print(w,end=' ') count+=1
f.close() print('Count of father,mother is', count)
TwoCharWord() COUNT()
Write a method/function COUNTLINES_ET() in Write a method/function SHOW_TODO() in python
python to read lines from a text file REPORT.TXT, to read contents from a text file ABC.TXTand display
and COUNT those lines which are starting either those lines which have occurrence of the word ‘‘TO’’
with ‘E’ and starting with ‘T’ respectively. And or ‘‘DO’’.
display the Total count separately. def SHOW_TODO():
def COUNTLINES_ET(): f=open(“ABC.TXT”)
f=open(“REPORT.TXT”) d=f.readlines()
d=f.readlines() for i in d:
le=0 if “TO” in i or “DO” in i:
lt=0 print(i)
for i in d: f.close()
if i[0]==’E’: SHOW_TODO()
le=le+1
elif i[0]==’T’:
lt=lt+1
print(“no of line start with”,le)
print(“no of line start with”,lt)
COUNTLINES_ET()
Write a function in Python that counts the Write a function AMCount() in Python, which
number of “Me” or “My” words present in a text should read each character of a text file
file “STORY.TXT”. STORY.TXT, should count and display the
def displayMeMy(): occurrences of alphabets A and M (including
num=0 small cases a and m too).
f=open("story.txt","rt") def AMCount():
N=f.read() f=open("story.txt","r")
M=N.split() NA,NM=0,0
for x in M: r=f.read()
if x=="Me" or x== "My": for x in r:
print(x) if x=="A" or x=="a" :
num=num+1 NA=NA+1
print("Count of Me/My in file:",num) elif x=="M" or x=="m":
f.close() NM=NM+1
print("A or a: ",NA)
displayMeMy() print("M or m: ",NM)
f.close()
AMCount()
4 AG NOTES
Write a function in python that displays the Write a function countmy() in Python to read file
number of lines starting with ‘H’ in the file Data.txt and count the number of times “my” occur
“para.txt”. in file.
def countH(): def countmy():
f=open("para.txt","r") f=open(“Data.txt”,”r”)
lines=0 count=0
l=f.readlines() x=f.read()
for i in l: word=x.split()
if i[0]='H': for i in word:
lines+=1 if i ==”my” :
print("NO of lines are:",lines) count=count+1
f.close() print(“my occurs “, count, “times”)
countH() countmy()
Write a Python program to find the number of Write a Python program to count the word “if “ in a
lines in a text file ‘abc.txt’. text file abc.txt’.
f=open("abc.txt","r") file=open("abc.txt","r")
d=f.readlines() c=0
count=len(d) line = file.read()
print(count) word = line.split()
f.close() for w in word:
if w=='if':
c=c+1
print(c)
file.close()
Write a method in python to read lines from a Write a method/function ISTOUPCOUNT() in python
text file DIARY.TXT and display those lines which to read contents from a text file WRITER.TXT, to
start with the alphabets P. count and display the occurrenceof the word ‘‘IS’’ or
def countp(): ‘‘TO’’ or ‘‘UP’’
f=open("diary.txt","r")
lines=0 def ISTOUPCOUNT():
l=f.readlines() c=0
for i in l: file=open('sample.txt','r')
if i[0]='P': line = file.read()
lines+=1 word = line.split()
print("No of lines are:",lines) cnt=0
countp() for w in word:
if w=='TO' or w=='UP' or w=='IS':
cnt+=1
print(cnt)
file.close()
ISTOUPCOUNT()
5 AG NOTES
Write a code in Python that counts the number of Write a function VowelCount() in Python, which
“The” or “This” words present in a text file should read each character of a text file
“MY_TEXT_FILE.TXT”. MY_TEXT_FILE.TXT, should count and display the
occurrence of alphabets vowels.
c=0
f=open('MY_TEXT_FILE.TXT', 'r') : def VowelCount():
d=f.read() count_a=count_e=count_i=count_o=count_u=0
w=d.split() f= open('MY_TEXT_FILE.TXT', 'r')
for i in w: d=f.read()
if i.upper()== 'THE' or i.upper()== 'THIS' : for i in d:
c+=1 if i.upper()=='A':
print(c) count_a+=1
elif letter.upper()=='E':
count_e+=1
elif letter.upper()=='I':
count_i+=1
elif letter.upper()=='O':
count_o+=1
elif letter.upper()=='U':
count_u+=1
print("A or a:", count_a)
print("E or e:", count_e)
print("I or i:", count_i)
print("O or o:", count_o)
print("U or u:", count_u)
f.close()
VowelCount()
Write a function filter(oldfile, newfile) that copies Write a function display() in Python, which should
all the lines of a text file “source.txt” onto read each character of a text file “poem.txt”, it should
“target.txt” except those lines which starts with display the lines ending with ‘!’.
“@” sign.
def display():
def filter(oldfile, newfile): f= open("poem.txt","r")
f1 = open("oldfile","r") m=f.readlines()
f2 = open(“newfile”,”w”) for i in m:
while True: if i[-2]=='!':
text= f1.readline() print(i)
if len(text) ==0: display()
break OR
if text[0] == ‘@’: Def display():
continue f=open('ss.txt', 'r')
f2.write(text) m=f.readlines()
f1.close() for i in m:
f2.close() if '!' in i:
oldfile=input(‘name of the old file’) print(i)
newfile= input(‘name of the new file’)
filter(oldfile, newfile)
6 AG NOTES