Python-Text Files (1)
Python-Text Files (1)
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.
Buffer: transfer of data between RAM and backing storage cannot be done directly because application
(program) has no clue about the backing storage. It is the OS (Operating System) that controls the backing
storage. Hence the solution is to create a temporary storage in the RAM called buffer to transfer data
between RAM and backing storage.
RAM HDD (Backing storage)
Variable(s) Python Program OS (Operating System)
Write Write
Writing into a file: data from the variable(s) located in the RAM to be transferred to the buffer by the
Python Program and data from the buffer to be transferred to the file located in the backing storage by the
OS (Operating System).
Reading from a file: data from file(s) located in the backing storage to be transferred to the buffer by the
OS (Operating System) and data from buffer to be transferred to the variable(s) located in the RAM by
the Python Program.
How to write into a file? In Python data can be written into file (via buffer) in two ways:
Using file object method write()
Syntax: fileobject.write(string)
Function write() will transfer a string into a buffer.
fileobject is a Python object which is created with open()
string is the data to be transferred to a buffer
Example #1: fw=open('costo.txt', 'w')
s1='3 days weekend because of Easter.\n'
s2='Sunday Test postponed to Monday.\n'
fw.write(s1) #transfers content of s1 to buffer
fw.write(s2) #transfers content of s2 to buffer
fw is the file object (fw – file write)
'costo.txt' is the file name
'w' is the mode, 'w' stands for write mode
s1, s2 are the string variables
FAIPS, DPS Kuwait Page 2 / 19 ©Bikram Ally
Python Notes Class XII Text File
Example #2: fw=open('costo.txt', 'w')
co,na,bs=1130, 'SURYA KRISHNA', 95700.0
rec=str(co)+','+na+','+str(bs)+'\n'
#co and bs converted to string
fw.write(rec) #transfers content of rec to buffer
fw is the file object (fw – file write)
'costo.txt' is the file name
'w' is the mode, 'w' stands for write mode
rec is the string variable
How to read from a file? In Python data can be read from a file (via buffer) in four ways:
Using file object method read()
Syntax: strvar=fileobject.read()
Function read() will transfer content of an entire file into a string variable from a buffer
fileobject is a Python object which is created with open()
strvar is the data (string variable) to store the entire file as a single string, read from
a buffer
Example #1: fr=open('costo.txt', 'r')
data=fr.read()
#data - is a string(entire file), read from a buffer
fr is the file object (fr – file read)
'costo.txt' is the file name
'r' is the mode, 'r' stands for read mode
data is the string variable
Example #2: fr=open('costo.txt', 'r')
data=fr.read(100)
#data – string of 100 characters, read from a buffer
FAIPS, DPS Kuwait Page 3 / 19 ©Bikram Ally
Python Notes Class XII Text File
fr is the file object (fr – file read)
'costo.txt' is the file name
'r' is the mode, 'r' stands for read mode
data is the string variable
How to close a file? In Python, a file is closed with close() method of a file object created using open()
and it carries out two actions:
When writing into a file, if a file is not closed, entire data may not be written in the file, that is, there could
be loss of data.
Syntax: fileobject.close()
File will be closed, no more data transfer between the RAM and the backing storage
fileobject is a Python object which is created with open()
Example #1: fw=open('costo.txt', 'w')
#Write operation in file
fw.close()
fw is the file object (fw – write read)
'costo.txt' is the file name
'w' is the mode, 'w' stands for write mode
Example #2: fr=open('costo.txt', 'r')
#Read operation from a file
fr.close()
fr is the file object (fr – file read)
'costo.txt' is the file name
'r' is the mode, 'r' stands for read mode
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 file and for reading from a file. There are more methods
available from a file object, which were not discussed because they are not included in the syllabus.
However, we will discuss three attributes (not methods) of a file object:
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' or 'wt' or 'tw' a text file is opened for write mode
'a' or 'at' or 'ta' a text file is opened for append mode
'r' or 'rt' or 'tr' a text 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') #OR fw=open('FILE3.TXT', 'wt')
fa=open('FILE2.TXT', 'a') #OR fa=open('FILE3.TXT', 'at')
fr=open('FILE3.TXT', 'r') #OR fr=open('FILE3.TXT', 'rt')
print(fw.name, fw.mode, fw.closed)
print(fa.name, fa.mode, fa.closed)
print(fr.name, fr.mode, fr.closed)
fw.close()
fa.close()
fr.close()
print(fw.name, fw.mode, fw.closed)
print(fa.name, fa.mode, fa.closed)
print(fr.name, fr.mode, fr.closed)
1. Write a Python program to create a text file 'costo.txt' by adding following lines in the file:
Execution of the program will generate a text file 'costo.txt', but the file 'costo.txt' will be empty (no
data was transferred to the file 'costo.txt') because file was not closed. So, what are possible solutions:
Close the file
s1='Costo with its first store in Khaitan has\n'
s2='positioned itself as a cost-effective\n'
s3='shopping destination. Costo is all set\n'
s4='to open its second outlet in Fahaheel.\n'
fw=open('costo.txt', 'w')
fw.write(s1)
fw.write(s2)
fw.write(s3)
fw.write(s4)
fw.close()
OR,
lines='''Costo with its first store in Khaitan has
positioned itself as a cost-effective
shopping destination. Costo is all set
to open its second outlet in Fahaheel.\n'''
#lines is a multi-line string
fw=open('costo.txt', 'w')
fw.write(lines)
fw.close()
Opening a file using keyword with, will automatically close the file without fw.close().
2. Write a Python program to add following lines in an existing text file 'costo.txt'.
Executing the Python program will create a text file 'costo.txt' and the content of the will be
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
To add more data to an existing file, without data loss, a file must be open in append mode. Edited
program is given below by opening the file in append mode ('a').
File object method write() will only write a single string into a file (via buffer). 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()
FAIPS, DPS Kuwait Page 7 / 19 ©Bikram Ally
Python Notes Class XII Text File
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()
Running of the program produces following output (read() will read the entire file as a single string):
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)
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
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.
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')
data=fr.readlines() #data is a list with a single string
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 everything has been
read from a file. 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.
Read and display the text file 'costo.txt' and at the end display number of lines present in the file.
Read and display the text file 'costo.txt' and at the end display number of words present in the file.
Read and display the text file 'costo.txt' and at the end display number of characters present in the
file.
Read and display the text file 'costo.txt' and at the end display number of uppercase characters,
lowercase and number of digits present in the file.
Read and display the text file 'costo.txt' and at the end display number of special characters and
number of white space characters present in the file
Exit from the Menu
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()
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
FAIPS, DPS Kuwait Page 11 / 19 ©Bikram Ally
Python Notes Class XII Text File
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')
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)
FAIPS, DPS Kuwait Page 12 / 19 ©Bikram Ally
Python Notes Class XII Text File
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')
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')
FAIPS, DPS Kuwait Page 13 / 19 ©Bikram Ally
Python Notes Class XII Text File
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
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)
FAIPS, DPS Kuwait Page 14 / 19 ©Bikram Ally
Python Notes Class XII Text File
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)
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
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
#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
FAIPS, DPS Kuwait Page 16 / 19 ©Bikram Ally
Python Notes Class XII Text File
#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()
File Pointer
File pointer is an imaginary marker which indicate the position (location) in the file. The position is
represented in terms of bytes from the beginning of the file. Every time data is written into a file, file
pointer is updated automatically (file pointer moves forward). Every time data is read from a file, pointer
is automatically updated (file pointer moves forward). If a file is opened in either write mode or in read
mode, file pointer is positioned in the beginning of the file. Position of the file pointer in the beginning of
the file is 0 (zero). If a file is opened in append mode, file pointer is positioned at the end of the file (last
bye of the file). A Python file object supports two functions related to file pointer:
tell() returns the position of the file pointer from the beginning of the file in bytes.
seek(pos) moves the file pointer to pos byte from the beginning of the file
seek(pos, whence) moves the file pointer pos bytes forward or pos byes backward from whence
whence is 0 from the beginning of the file
whence is 1 from the current position in the file
whence is 2 from the end of the file
A text file supports tell() and seek(pos) but does not support seek(pos, whence). A binary
file supports all three functions. A program is given below showing the position of the file pointer after
writing line of text into a text file in write mode.
fobj=open('FOO.TXT', 'w')
print('Position of File Pointer=', fobj.tell())
for x in range(6):
line=input('Code,Name,BSal? ')
fobj.write(line+'\n')
print('Position of File Pointer after',x+1,'line=',fobj.tell())
fobj.close()
Text file 'FOO.TXT' is opened in write mode, position of the file pointer is in the beginning of the file,
that is, 0 (zero). After writing a line of text, file pointer is advanced automatically. A program is given
below showing the position of the file pointer after reading a text file line by line.
fobj=open('FOO.TXT')
print('Position of File Pointer=', fobj.tell())
for line in fobj: print(line.strip(), fobj.tell())
fobj.close()
It is not surprising to note that the position of the file pointer is same after every line, in both modes. Since
the file is opened without any mode, the default mode is read mode. The number after every line is the
position of the file pointer after every line. A program is given below showing the position of the file
pointer after writing line of text into a text file in append mode.
fobj=open('FOO.TXT', 'a')
print('Position of File Pointer=', fobj.tell())
for x in range(4):
line=input('Code,Name,BSal? ')
fobj.write(line+'\n')
print('Position of File Pointer after',x+1,'line=',fobj.tell())
fobj.close()