Python-Text Files
Python-Text Files
Why do we need file? We need file to store data (programs) because RAM (main storage) is volatile –
data and program cannot be stored permanently and RAM (main storage) has limited capacity
What is backing storage? Backing storage is a storage device where data and programs can be stored
permanently. Until and unless user decides to delete the file from the backing storage, the file will remain
permanently.
How to close a file? In Python, a file is closed with close() method of a file object created using open().
Method close()ensures that all data are written successfully into a file. When writing into a file (write /
append mode), if a file is not closed, entire data may not be written into the file. There could be loss of
data. So, it is mandatory for the programmer to close a file, when a file is opened in write / append mode.
Syntax: fileobject.close()
File will be closed, no more data transfer between RAM and the backing storage
fileobject is a Python object which is created with open()
Example #1:
fobj=open('any.txt','w') #opens a file in write mode
#fobj=open('any.txt','a') #opens a file in append mode
fobj.close()
fobj is the file object (fw – write read)
'any.txt' is the file name
'w' is the mode, 'w' stands for write mode
Example #2:
fobj=open('any.txt','r') #opens a file in read mode
#fobj=open('any.txt') #opens a file in default(read) mode
fobj.close()
fobj is the file object
'any.txt' is the file name
'r' is the mode, 'r' stands for read mode
How to write into a text file? In Python data can be written into a text file in two ways:
• Using file object method write()
Syntax: fileobject.write(string)
File object method write() will transfer a string into a text file and it returns int.
fileobject is a Python object which is created with open()
string is the data to be written into a file
Example #1:
fobj=open('costo.txt', 'w')
s1='3 days weekend because of Easter.\n'
s2='Sunday Test postponed to Monday.\n'
fobj.write(s1) #writes content of s1 into costo.txt
fobj.write(s2) #writes content of s2 into costo.txt
fobj.close()
fobj is the file object
When a file is opened, a file object is created. A file object has many methods (functions belonging to an
object) as discussed above for writing into a text file and for reading from a text file. Also, there are other
members available from a file object. Members of an object which is not function is generally called
attribute. File object has few attributes and three attributes are explained below:
• Attribute closed: closed will have value False if the file is open and it will have value True if
the file is closed.
• Attribute mode: mode will store the mode of the file.
'w' for a text file is opened for write mode
'a' for a text file is opened for append mode
'r' for a text file is opened for read mode (default mode)
'wb' for a binary file is opened for write mode
'ab' for a binary file is opened for append mode
'rb' for a binary file is opened for read mode (default mode)
• Attribute name: name will store the name of a file.
Python script is given below showing the use of file object attributes closed, mode and name:
fw=open('FILE1.TXT', 'w') #fw=open('FILE3.TXT', 'wt')
fr=open('FILE2.TXT', 'r') #fr=open('FILE2.TXT', 'rt')
f1=open('DATA1.DAT', 'ab') #f1=open('DATA1.DAT', 'ba')
f2=open('DATA2.DAT', 'rb') #f2=open('DATA2.DAT', 'rb')
print(fw.name, fw.mode, fw.closed)
print(fr.name, fr.mode, fr.closed)
print(f1.name, f1.mode, f1.closed)
print(f2.name, f2.mode, f2.closed)
fw.close(); fr.close(); f1.close(); f2.close()
print(fw.name, fw.mode, fw.closed)
print(fr.name, fr.mode, fr.closed)
print(f1.name, f1.mode, f1.closed)
print(f2.name, f2.mode, f2.closed)
2. Write a Python program to add following lines in an existing text file 'costo.txt'.
Costo is part of Regency Group which is among
the foremost retail players in GCC region.
s1=' Costo is part of Regency Group which is among\n'
s2=' the foremost retail players in GCC region.\n’
fw=open('costo.txt', 'W')
fw.write(s1)
fw.write(s2)
fw.close()
Executing the Python program will create a text file 'costo.txt' and the content of the will be
Costo is part of Regency Group which is among
the foremost retail players in GCC region.
That is, previous content of the text file has been overwritten by new set of data. Now it is important
to remember when a file is opened in write mode ('w'):
• If the file does not exist, a new file is created
• If the file exists, new set of data will overwrite the existing data in the file, there will be loss
of data
File object method write() will only write a single string into a file. As discussed earlier, one can use
file object method wrilelines() to write a list of string into a file (via buffer). A Python program to
write a list of string into a file is given in the next page.
data=['Costo with its first store in Khaitan has\n',
'positioned itself as a cost-effective\n',
'shopping destination. Costo is all set\n',
'to open its second outlet in Fahaheel.\n']
fw=open('costo.txt', 'w')
fw.writelines(data)
fw.close()
OR,
data=['Costo with its first store in Khaitan has\n',
'positioned itself as a cost-effective\n',
'shopping destination. Costo is all set\n',
'to open its second outlet in Fahaheel.\n']
with open('costo.txt', 'w') as fw: fw.writelines(data)
3. Write a Python program to read and display a text file 'costo.txt' using file object method read().
fr=open('costo.txt', 'r')
data=fr.read()
print(data)
fr.close()
4. Write a Python program to read a text file 'costo.txt' using file object method read() but display first
182 characters.
fr=open('costo.txt', 'r')
data=fr.read(182)
print(data)
fr.close()
5. Write a Python program to read and display a text file 'costo.txt' using file object method readline().
fr=open('costo.txt', 'r')
data=fr.readline()
while data:
print(data.strip())
data=fr.readline()
fr.close()
in GCC region.
Why there a blank line after every line? This is because every line in the text file 'costo.txt' is
terminated by a new line character ('\n') plus print() function is also add a new line character on
the screen. To remove the blank lines from the output, there are two solutions: either remove the new
line character from the print() function or remove the new line character from the string read from the
file. Edit program without the blank lines is given below:
fr=open('costo.txt', 'r')
data=fr.readline()
while data:
print(data.strip()) #print(data,end='')
data=fr.readline()
fr.close()
while loop will execute till data!="" is true. Variable data will be "" (empty string) when nothing
can be read from the file end of the file. Function print(data.strip()) – removes all the white
FAIPS, DPS Kuwait Page 8 / 16 ©Bikram Ally
Python Notes Class XII Text File
space (space / tab / new line) characters from the beginning and from the end of the string.
print(data,end='') – does not display the default new line character on the screen.
6. Write a Python program to read and display a text file 'costo.txt' using file object method readlines().
fr=open('costo.txt', 'r')
data=fr.readlines()
fr.close()
for line in data: print(line.strip())
File object method readlines() will read the entire file as a list of strings and store it in a variable
data. for loop displays the data on the screen.
7. Write a Python program to read and display a text file 'costo.txt' using file object as an iterator.
fr=open('costo.txt', 'r')
for line in fr: print(line.strip())
fr.close()
8. Write a Python program to read and display a text file 'costo2.txt'. File 'costo2.txt' does not have any
new character in the file.
fr=open('costo2.txt', 'r')
data=fr.read()
print(data)
fr.close()
OR,
fr=open('costo2.txt', 'r')
data=fr.readline()
print(data)
fr.close()
fr=open('costo2.txt', 'r')
data1=fr.read() #First fr.read()
data2=fr.read() #Second fr.read()
print(data1)
print(date2)
fr.close()
File costo2.txt will be displayed once because print(data1) will display the file but
print(data2) will display an empty string, so a blank line will be displayed on the screen. Why?
First fr.read() will read the entire file and the file will be stored as string in the variable data1.
Next, the file will encounter End Of File. What is End Of File? It simply means nothing else is left
to be read. So first fr.read() has read everything from the file, second fr.read() has nothing
to read (beyond end of the file), hence data2 will represent an empty string.
def addlines():
data= [ 'COSTO is a customer driven purchase\n',
'store where customer feedbacks determine\n',
'the future products in the store.\n' ]
fw=open('Costo.txt', 'a')
fw.writelines(data)
fw.close()
FAIPS, DPS Kuwait Page 10 / 16 ©Bikram Ally
Python Notes Class XII Text File
OR,
def addlines():
line1='COSTO is a customer driven purchase\n'
line2='store where customer feedbacks determine\n',
line3='the future products in the store.\n'
fw=open('Costo.txt', 'a')
fw.write(line1)
fw.write(line2)
fw.write(line3)
fw.close()
OR,
def addlines():
lines='''COSTO is a customer driven purchase
store where customer feedbacks determine
the future products in the store.\n'''
fw=open('Costo.txt', 'a')
fw.writelines(lines)
fw.close()
OR,
def addlines():
lines='COSTO is a customer driven purchase\nstore where customer
feedbacks determine\nthe future products in the store.\n'
fw=open('Costo.txt', 'a')
fw.writelines(lines)
fw.close()
OR,
def addlines():
lines='''COSTO is a customer driven purchase
store where customer feedbacks determine
the future products in the store.\n'''
with open('Costo.txt', 'a') as fw;
fw.writelines(lines)
def countlines():
fr=open('Costo.txt', 'r')
c=0
for line in fr:
print(line.strip())
c+=1
fr.close()
print('Number of lines=',c)
def countwords():
fr=open('Costo.txt', 'r')
c=0
for line in fr:
print(line.strip())
words=line.split()
c+=len(words)
fr.close()
print('Number of words=',c)
OR,
def countwords():
fr=open('Costo.txt', 'r')
FAIPS, DPS Kuwait Page 11 / 16 ©Bikram Ally
Python Notes Class XII Text File
data=fr.read()
fr.close()
print(data.strip())
words=data.split()
print('Number of words=',len(words))
def countcharacters():
fr=open('Costo.txt', 'r')
c=0
for line in fr:
print(line.strip())
c+=len(line)
fr.close()
print('Number of characters=',c)
OR,
def countcharacters():
fr=open('Costo.txt', 'r')
data=fr.read()
fr.close()
print(data.strip())
print('Number of characters=',len(data))
def countupperlowerdigit():
fr=open('Costo.txt', 'r')
c1=c2=c3=0
for line in fr:
print(line.strip())
if ch>='A' and ch<='Z': c1+=1
#if 'A'<=ch<='Z': c1+=1
#if ch.isupper(): c1+=1
elif ch>='a' and ch<='z': c2+=1
#elif 'a'<=ch<='z': c2+=1
#elif ch.islower(): c2+=1
elif ch>='0' and ch<='9': c3+=1
#elif '0'<=ch<='9': c3+=1
#elif ch.isdigit(): c3+=1
fr.close()
print('Number of Uppercase=',c1)
print('Number of Lowercase=',c2)
print('Number of Digits =',c3)
def countspecial():
fr=open('Costo.txt', 'r')1
data=fr.read()
fr.close()
print(data.strip())
c=0
for ch in data:
if ch.isalpha()==False: c+=1
#if not ch.isalpha(): c+=1
print('Number of Special characters=',c)
OR,
def countspecialwhitespace():
fr=open('Costo.txt', 'r')
FAIPS, DPS Kuwait Page 12 / 16 ©Bikram Ally
Python Notes Class XII Text File
data=fr.read()
fr.close()
print(data.strip())
c1=c2=0
for ch in data:
if 'A'<=ch<='Z' or 'a'<=ch<='z' or '0'<=ch<='9': c1+=1
#if ch.isalpha(): c1+=1
if ch==' ' or ch=='\t' or ch=='\n': c2+=1
#if ch in ' \t\n': c2+=1
print('Number of Special characters=',len(dat)-c1)
print('Number of White-space characters=',c2)
OR,
def countspecialwhitespace():
fr=open('Costo.txt', 'r')
data=fr.read()
fr.close()
print(data.strip())
c1=c2=0
for ch in data:
if not ('A'<=ch<='Z' or 'a'<=ch<='z' or '0'<=ch<='9'): c1+=1
'''
if 'A'<=ch<='Z' or 'a'<=ch<='z' or '0'<=ch<='9': pass
else: c1+=1
'''
if ch==' ' or ch=='\t' or ch=='\n': c2+=1
#if ch in ' \t\n': c2+=1
print('Number of Special characters=',c1)
print('Number of White-space characters=',c2)
while True:
print('1. Append Lines')
print('2. Count Lines')
print('3. Count Words')
print('4. Count Number of Characters')
print('5. Count Uppercase, Lowercase & Digit')
print('6. Count Special & White-space Characters')
print('0. Exit')
ch=input('Choice[0-5]? ')
if ch=='1': addlines()
elif ch=='2': countlines()
elif ch=='3': countwords()
elif ch=='4': countcharacters()
elif ch=='5': countupperlowerdigit()
elif ch=='6': countspecialwhitespace()
elif ch=='0': break
Write a Python function to read and display a text file AIRBUS.TXT on the screen. At the end display
number of uppercase vowels and number of lowercase vowels present in the file.
def countvowels():
fobj=open('AIRBUS.TXT')
mytext=fobj.read()
fobj.close()
print(mytext)
c1=c2=0
FAIPS, DPS Kuwait Page 13 / 16 ©Bikram Ally
Python Notes Class XII Text File
for ch in mytext:
if ch in 'AEIOU': c1+=1
if ch in 'aeiou': c2+=1
print('Uppercase vowels=', c1)
print('Lowercase vowels=', c2)
Write a Python function to read and display a text file AIRBUS.TXT on the screen. At the end display
number of uppercase consonants, number of uppercase vowels, number of number of lowercase
consonants, number of lowercase vowels present in the file.
def countconsonantsvowels():
fobj=open('AIRBUS.TXT')
mytext=fobj.read()
fobj.close()
print(mytext)
c1=c2=c3=c4=0
for ch in mytext:
if 'A'<=ch<='Z': #if ch>='A' and ch<='Z':
#if ch.isupper():
if ch in 'AEIOU': c1+=1
else: c2+
if 'a'<=ch<='z': #if ch>='a' and ch<='z':
#if ch.islower():
if ch in 'aeiou': c3+=1
else: c4+=1
print('Uppercase vowels=', c1)
print('Uppercase consonants=', c2)
print('Lowercase vowels=', c3)
print('Lowercase consonants=', c4)
Write a Python function to display the text file AIRBUS.TXT on the screen. At end display number of
times 'THE' appear in the file (count ignoring case).
def countword():
fobj=open('AIRBUS.TXT')
mytext=fobj.read()
fobj.close()
print(mytext)
wordlist=mytext.split()
c=0
for word in wordlist:
if word.upper()=='THE': c+=1
print('"THE" appears=', c)
Write a Python function to display the text file AIRBUS.TXT on the screen. At end display number words
either starting with 'A'/'a' or starting with 'T'/'t' present in the text file.
def countword():
fobj=open('AIRBUS.TXT')
mytext=fobj.read()
fobj.close()
print(mytext)
wordlist=mytext.split()
c=0
for word in wordlist:
if word[0] in 'AaTt': c+=1
print('Words starting with "A/a/T/t"=', c)
FAIPS, DPS Kuwait Page 14 / 16 ©Bikram Ally
Python Notes Class XII Text File
Write a Python function to display the text file AIRBUS.TXT on the screen. At end display number words
either ending with 'E'/'e' or ending with 'I'/'i' present in the text file.
def countword():
fobj=open('AIRBUS.TXT')
mytext=fobj.read()
fobj.close()
print(mytext)
wordlist=mytext.split()
c=0
for word in wordlist:
if word[-1] in 'EeIi': c+=1
print('Words ending with "E/e/I/i"=', c)
Write a Python function to display the text file AIRBUS.TXT on the screen. At end display number words
containing at least two vowels present in the text file (ignore case when counting vowels).
def countword():
fobj=open('AIRBUS.TXT')
mytext=fobj.read()
fobj.close()
print(mytext)
wordlist=mytext.split()
c1=0
for word in wordlist:
c2=0
for ch in word:
if ch.upper() in 'AEIOU': c1+=1
#if ch.lower() in 'aeiou': c1+=1
if c2>1: c1+=1
print('Number of words having at least 2 vowels=', c1)
Write a Python function to display the text file AIRBUS.TXT on the screen. At end display number words
starting with a vowel and ending with a vowel present in the text file (ignore case when counting vowels).
def countword():
fobj=open('AIRBUS.TXT')
mytext=fobj.read()
fobj.close()
print(mytext)
wordlist=mytext.split()
c=0
for word in wordlist:
ch1, ch2=word[0].upper(), word[-1].upper()
#ch1, ch2=word[0].lower(), word[-1].lower()
if ch1 in 'AIEOU' and ch2 in 'AEIOU': c+=1
#if ch1 in 'aieou' and ch2 in 'AEIOU': c+=1
print('Words starting with vowel and ending with vowel=', c)
Write a Python function to read and display the text file AIRBUS.TXT on the screen. At end display
number of lines not ending with vowel in the text file (ignore case when checking for vowel).
def countline():
fobj=open('AIRBUS.TXT')
c=0
for line in fobj:
print(line.strip())
if line[-1].upper() not in 'AEIOU': c+=1
FAIPS, DPS Kuwait Page 15 / 16 ©Bikram Ally
Python Notes Class XII Text File
#if line[-1].lower() not in 'aeiou': c+=1
#if line[-1] not in 'AEIOUaeiou': c+=1
fobj.close()
print('Number of lines not ending with vowel=', c)
Write a Python function to read and display the text file AIRBUS.TXT on the screen. At end display
number of alphabets present in every line.
def countline():
fobj=open('AIRBUS.TXT')
for line in fobj:
c=0
for ch in line:
if 'A'<=ch<='Z' or 'a'<=ch<='z': c+=1
#if ch>='A' and ch<='Z' or ch>='a' and ch<='z': c+=1
#if ch.isalpha(): c+=1
print(line.strip(), c)
fobj.close()
Write a Python function to display the text file AIRBUS.TXT on the screen. At end display number of
digits and number of special characters present in every line.
def countline():
fobj=open('AIRBUS.TXT')
for line in fobj:
c1=c2=0
for ch in line:
if '0'<=ch<='9': c1+=1
#if ch>='0' and ch<='9': c1+=1
#if ch.isisdigit(): c1+=1
if ch.isalpha()==False: c2+=1
#if not ch.isalpha(): c2+=1
#if not ('A'<=ch<='Z' or 'a'<=ch<='z' or '0'<=ch<='9'): c2+=1
'''
if 'A'<=ch<='Z' or 'a'<=ch<='z' or '0'<=ch<='9': pass
else: c2+=1
'''
print(line.strip(), c1, c2)
fobj.close()