0% found this document useful (0 votes)
5 views

Python-Text Files (1)

Uploaded by

Mohammed Fahad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python-Text Files (1)

Uploaded by

Mohammed Fahad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Python Notes Class XII Text File

File: is either data or program stored in a backing storage permanently.

Why do we need file? We need file because:


 RAM (main storage) is volatile – data and program cannot be stored permanently
 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.

Commonly used backing storage:


1. Magnetic Storage: Internal Hard Disk Drive, Portable Hard Disk, Magnetic Tape and obsolete Floppy
disk
2. Electronic Storage: Solid State Drive, Portable Solid State Drive, USB Flash Drive (Pen Drive) and
SD Card
3. Optical Storage: CD, DVD and Blu-Ray Disc

A file can be stored in the backing storage as:


 Text file – file stored in the backing storage in human readable format. Text file can be read and edited
using any text editor like Notepad.
 Binary file – file stored in the backing storage in machine readable format. Binary file can be read and
edited with the application (program) that created the binary file.

There are two basic operations in a file:


 Write into a file – data is transferred from variable(s) located in the RAM to file(s) located in the
backing storage
 Read from a file – data is transferred from file(s) located in the backing storage to the variable(s)
located in the RAM

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

Data Buffer REPORT.TXT


Read Read

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.

Three basic steps when working with file in Python:


 Open a file
 Write into a file via buffer
OR, Read from a file via buffer
 Close file

FAIPS, DPS Kuwait Page 1 / 19 ©Bikram Ally


Python Notes Class XII Text File
How to open a file? In Python a file can be opened in two ways:
 Using built-in independent function open()
Syntax: fileobject=open(filename, mode)
Function open() will create a file object and allocate a buffer in the RAM for the file
filename so that all data transfer between RAM and backing storage is through the buffer.
fileobject is a Python object which is created with open()
filename name of the file and file name is a string
mode write ('w') mode / append ('a') mode / read ('r') mode and if mode is
omitted, default mode is the read mode
Example #1: fw=open('costo.txt', 'w')
fw is the file object (fw – file write)
'costo.txt' is the file name
'w' is the mode, 'w' stands for write mode

Example #2: fa=open('costo.txt', 'a')


fa is the file object (fa – file append)
'costo.txt' is the file name
'a' is the mode, 'a' stands for append mode
Difference between write mode and append mode (special type of write mode) will be
discussed later.

Example #3: fr=open('costo.txt', 'r')


#OR, fr=open('costo.txt')
Default mode is read mode.
fr is the file object (fr – file read)
'costo.txt' is the file name
'r' is the mode, 'r' stands for read mode

 Using keyword with and function built-in independent open()


Syntax: with open(filename, mode) as fileobject:
Function open() will allocate a buffer in the RAM for the file filename.
with is the keyword
fileobject is a Python object which is created with open()
filename name of the file and file name is a string
mode write mode / append mode / read mode
Difference between opening a file with or without with will be discussed later.

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

 Using file object method writelines()


Syntax: fileobject.writelines(strlist)
Function writelines() will transfer a list of strings into a buffer.
fileobject is a Python object which is created with open()
strlis is the data (strlist) – a list of strings to be transferred to a buffer
Example #1: fw=open('costo.txt', 'w')
data=['APPLE\n','MANGO\n','ORANGE\n','GRAPES\n']
fw.writelines(data)
#transfers content of data (list of str) 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
data is the list of strings (variable)
Example #2: fw=open('costo.txt', 'w')
data=['1130, ATUL JAIN, 95700.0\n',
'1132, GAURAV KUMAR,97600.0\n',
'1134, TEENA PAUL, 93500.0\n',
'1136, SUNILA GARG, 94700.0\n']
fw.writelines(data)
#transfers content of data (list of str) 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
data is the list of strings (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

 Using file object method readline()


Syntax: strvar=fileobject.readline()
Function readline() will transfer a line of text (string - till a new line character is
encountered or reads the entire file when there is no new line character present in the file)
from a buffer to a string variable
fileobject is a Python object which is created with open()
strvar is the data (string variable) to store a line of text (string) read from a buffer
Example #1: fr=open('costo.txt', 'r')
data=fr.readline()
#data is a line of text (string), 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

 Using file object method readlines()


Syntax: listofstr=fileobject.readlines()
Function readlines() will transfer entire data from a buffer to a list of strings
fileobject is a Python object which is created with open()
listofstr is the data (list of strings) to store an entire file, read from a buffer, assuming
every line is terminated by a new line character and if there are no new line characters
present in the file, then a list will be created with a single string
Example #1: fr=open('costo.txt', 'r')
data=fr.readlines()
#data - list of strings (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 list of strings

 Using for loop and file object as an iterator list


Syntax: for line in fileobject:
#Python code
fileobject is a Python object which is created with open()
line will represent a line of text (string) read from the text file through the
fileobject from a buffer
Example #1: fr=open('costo.txt', 'r')
for data in fr: print(data)
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 a string (line of text)

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:

FAIPS, DPS Kuwait Page 4 / 19 ©Bikram Ally


Python Notes Class XII Text File
 It flushes (empties) the content of the buffer – OS transfers data from a buffer to the file located in the
backing storage.
 Buffer that was allocated to the file using built-in independent function open(), is de-allocated, that is,
no more data transfer is possible between the RAM and the backing storage.

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)

Running of the scripts produces following outputs:


FILE1.TXT w False
FILE2.TXT a False
FAIPS, DPS Kuwait Page 5 / 19 ©Bikram Ally
Python Notes Class XII Text File
FILE3.TXT r False
FILE1.TXT w True
FILE2.TXT a True
FILE3.TXT r True

1. Write a Python program to create a text file 'costo.txt' by adding following lines in the file:

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.

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)
#Function fw.close() is missing

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()

 Open file using keyword with


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'
with open('costo.txt', 'w') as fw:
fw.write(s1)
fw.write(s2)
FAIPS, DPS Kuwait Page 6 / 19 ©Bikram Ally
Python Notes Class XII Text File
fw.write(s3)
fw.write(s4)

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'.

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

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').

Write Mode Append Mode


 If a file does not exist, a new file is created  If a file does not exist, a new file is created
 If a file exists, new data overwrites the  If a file exists, new data will be written at the
existing data in the file => loss of data end of the file => no loss of data

s1=' Costo is part of Regency Group which is among\n'


s2=' the foremost retail players in GCC region.\n’
fa=open('costo.txt', 'a')
fa.write(s1)
fa.write(s2)
fa.close()

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):

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.
Costo is part of Regency Group which
is among the foremost retail players
in GCC region.

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()

Running of the program produces following output:

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.
Costo is part of Regency

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()

Running of the program produces following output:


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.


FAIPS, DPS Kuwait Page 8 / 19 ©Bikram Ally
Python Notes Class XII Text File

Costo is part of Regency Group which

is among the foremost retail players

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()

Running of the Python program produces following output:


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.
Costo is part of Regency Group which
is among the foremost retail players
in GCC region.

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())

Running of the Python program produces following output:


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.
Costo is part of Regency Group which
is among the foremost retail players
in GCC region.

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.

FAIPS, DPS Kuwait Page 9 / 19 ©Bikram Ally


Python Notes Class XII Text File
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()

Running of the Python program produces following output:


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.
Costo is part of Regency Group which
is among the foremost retail players
in GCC region.

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()

Running either of the Python program will produce following output:


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. Costo is part of Regency Group which is
among the foremost retail players in GCC region.

In both the cases, data will be stored as a single string.

fr=open('costo2.txt', 'r')
data=fr.readlines() #data is a list with a single string
print(data)
fr.close()

Running of the Python program produces following output:


['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. Costo is part of Regency Group which is
among the foremost retail players in GCC region.']

fr=open('costo2.txt', 'r')
data1=fr.read() #First fr.read()
data2=fr.read() #Second fr.read()
print(data1)
print(date2)
fr.close()

FAIPS, DPS Kuwait Page 10 / 19 ©Bikram Ally


Python Notes Class XII Text File
Running Python program will produce following output:
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. Costo is part of Regency Group which is
among the foremost retail players in GCC region.

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.

9. Write a Python menu driven program to do the following:


 Append the following files in an existing text file 'costo.txt':

COSTO is a customer driven purchase


store where customer feedbacks determine
the future products in the store.

 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)

FAIPS, DPS Kuwait Page 15 / 19 ©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
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
#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()

Running of the program produces following output:


Position of File Pointer= 0

FAIPS, DPS Kuwait Page 17 / 19 ©Bikram Ally


Python Notes Class XII Text File
Code,Name,BSal? 11001,SHANKAR,140000
Position of File Pointer after 1 line= 22
Code,Name,BSal? 11002,SANIA,130000
Position of File Pointer after 2 line= 42
Code,Name,BSal? 11003,KAMLESH,120000
Position of File Pointer after 3 line= 64
Code,Name,BSal? 11004,MANOJ,160000
Position of File Pointer after 4 line= 84
Code,Name,BSal? 11005,LOKESH,150000
Position of File Pointer after 5 line= 105
Code,Name,BSal? 11006,GAUTAM,120000
Position of File Pointer after 1 line= 126

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()

Running of the program produces following output:


Position of File Pointer= 0
11001,SHANKAR,140000 22
11002,SANIA,130000 42
11003,KAMLESH,120000 64
11004,MANOJ,160000 84
11005,LOKESH,150000 105
11006,GAUTAM,120000 126

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()

Running of the program produces following output:


Position of File Pointer= 126
Code,Name,BSal? 11007,SHALINI,140000
Position of File Pointer after 2 line= 148
Code,Name,BSal? 11008,RAHUL,170000
Position of File Pointer after 3 line= 168
Code,Name,BSal? 11009,KRITIKA,150000
Position of File Pointer after 4 line= 190
Code,Name,BSal? 11010,VIVEK,130000
Position of File Pointer after 5 line= 210

FAIPS, DPS Kuwait Page 18 / 19 ©Bikram Ally


Python Notes Class XII Text File
Since the file is opened in append mode, the file pointer is at the end of the file. So far we have seen the
use of tell() function. Now we will see the use of seek() function. As mentioned earlier, a text file
will only support seek(pos) function. A program is given below to read the lines from the text file
'FOO.TXT' is random order by using seek() function.
fobj=open('FOO.TXT')
Content of the file 'FOO.TXT’ along with
fobj.seek(64); line=fobj.readline()
position of the file pointer after every line.
print(line.strip())
11001,SHANKAR,140000 22
fobj.seek(168); line=fobj.readline()
11002,SANIA,130000 42
print(line.strip())
11003,KAMLESH,120000 64
fobj.seek(22); line=fobj.readline()
11004,MANOJ,160000 84
print(line.strip())
11005,LOKESH,150000 105
fobj.seek(105); line=fobj.readline()
11006,GAUTAM,120000 126
print(line.strip())
11007,SHALINI,140000 148
fobj.seek(190); line=fobj.readline()
11008,RAHUL,170000 168
print(line.strip())
11009,KRITIKA,150000 190
fobj.close()
11010,VIVEK,130000 210
Running of the program produces following output:
11004,MANOJ,160000
11009,KRITIKA,150000
11002,SANIA,130000
11006,GAUTAM,120000
11010,VIVEK,130000

Explanation of the outputs:


fobj.seek(64) moves the file pointer from the beginning of the file, to the end of the
third line and the beginning of the fourth line
line=fobj.readline() reads the fourth line from the file
print(line.strip()) displays the fourth line
fobj.seek(168) moves the file pointer from the beginning of the file, to the end of the
eight line and the beginning of the ninth line
line=fobj.readline() reads the ninth line from the file
print(line.strip()) displays the ninth line
fobj.seek(22) moves the file pointer from the beginning of the file, to the end of the
first line and the beginning of the second line
line=fobj.readline() reads the second line from the file
print(line.strip()) displays the second line
fobj.seek(105) moves the file pointer from the beginning of the file, to the end of the
fifth line and the beginning of the sixth line
line=fobj.readline() reads the sixth line from the file
print(line.strip()) displays the sixth line
fobj.seek(190) moves the file pointer from the beginning of the file, to the end of the
ninth line and the beginning of the last line
line=fobj.readline() reads the last line from the file
print(line.strip()) displays the last line

FAIPS, DPS Kuwait Page 19 / 19 ©Bikram Ally

You might also like