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

Python-Text Files

The document discusses files and file operations in Python. It defines a file as data or a program stored permanently in backing storage. RAM is volatile so files are needed to permanently store data and programs. Common backing storages include hard disks, SSDs, USB drives, and optical disks. Files can be text files stored in human-readable format or binary files stored in machine-readable format. The basic file operations in Python are writing data to a file and reading data from a file. Files are opened, data is written or read, and then files are closed. Files can be opened using the open() function or with statement and closed using the close() method. Data is written to text files using the write() and writel

Uploaded by

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

Python-Text Files

The document discusses files and file operations in Python. It defines a file as data or a program stored permanently in backing storage. RAM is volatile so files are needed to permanently store data and programs. Common backing storages include hard disks, SSDs, USB drives, and optical disks. Files can be text files stored in human-readable format or binary files stored in machine-readable format. The basic file operations in Python are writing data to a file and reading data from a file. Files are opened, data is written or read, and then files are closed. Files can be opened using the open() function or with statement and closed using the close() method. Data is written to text files using the write() and writel

Uploaded by

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

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

Commonly used backing storage:


1. Magnetic Storage: Internal Hard Disk Drive, Portable Hard Disk, Magnetic Tape and Floppy disk
2. Electronic Storage: Solid State Drive, Portable Solid State Drive, USB Flash 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 or CSV 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) or object(s) located in the RAM (main storage)
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) or
object(s) located in the RAM (main storage)

Three basic steps when working with file in Python:


• Open a file
• Write into a file OR, Read from a file
• Close 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 part of the RAM for the temporary
storage of the data before being transferred to the file located in the backing storage
fileobject is a Python object (variable) which is created with open()
filename name of the file located in the backing storage
file name is a string and generally file name has an extension
mode write ('w') mode / append ('a') mode / read ('r') / read-write mode ('w+'
/ 'a+' / 'r+'). If mode is missing, the default mode is the read mode
Example #1:
fobj=open('costo.txt', 'w')
fobj is the file object
'costo.txt' is the file name
'w' is the mode, 'w' stands for write mode
Example #2:
fobj=open('costo.txt', 'a')
fobj is the file object
'costo.txt' is the file name
'a' is the mode, 'a' stands for append mode
Difference between write mode and append mode will be discussed later.
FAIPS, DPS Kuwait Page 1 / 16 ©Bikram Ally
Python Notes Class XII Text File
Example #3:
fobj=open('costo.txt', 'r') #OR, fobj=open('costo.txt')
Default mode is read mode.
fobj 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 built-in independent function open()


Syntax: with open(filename, mode) as fileobject:
with is the keyword
Function open() will create a file object and allocate a part of the RAM for the temporary
storage of the data before being transferred to the file located in the backing storage
filename name of the file located in the backing storage
fileobject is a Python object which is created with open()
mode write mode / append mode / read mode / read-write mode

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

FAIPS, DPS Kuwait Page 2 / 16 ©Bikram Ally


Python Notes Class XII Text File
'costo.txt' is the file name
'w' is the mode, 'w' stands for write mode
s1, s2 are the string variables (objects)
Example #2:
fobj=open('salary.txt', 'w')
co,na,bs=1130,'KRISHNA',95700.0
rec=f'{co},{na},{bs}\n'
fobj.write(rec) #writes content of s1 into salary.txt
fobj.close()
fobj is the file object
'salary.txt' is the file name
'w' is the mode, 'w' stands for write mode
rec is the string variable (object)

• Using file object method writelines()


Syntax: fileobject.writelines(iterableobj)
File object method writelines() will transfer an iterable object (iterableobj) containing
strings into a text file. An iterable object can either be a single-line string, multi-line string,
list containing only strings, tuple containing only strings, dictionary where all keys are
strings. If an iterable like list or tuple or dictionary contains non-strings, writlines() will
trigger an error. Method writelines() returns None.
fileobject is a Python object which is created with open()
iterableobj is the data to be transferred into a file
Example:
fobj=open('anytext.txt', 'w')
s1='First Term Exam starts 23-May\n'
s2='''Last Exam is on 4-June
Result PTM on 15-June\n
Summer break begins from 16-June'''
s3={'ARUN':88, 'RITA':75, 'TARA':84, 'RAJA':82}
fobj.writelines(s1) #writes content of s1 into mytext.txt
fobj.writelines(s2) #writes content of s2 into mytext.txt
fobj.writelines(s3) #writes content of s3 into mytext.txt
fobj.close()
fobj is the file object
'mytext.txt' is the file name
'w' is the mode, 'w' stands for write mode
s1,s2,s3 are the iterable objects (variable) containing strings
Example #2:
fobj=open('employee.txt', 'w')
data1=['1130, ATUL JAIN, 95700.0\n',
'1132, GAURAV KUMAR,97600.0\n',
'1134, TEENA PAUL, 93500.0\n']
data2=('1136, SUNILA GARG, 94700.0\n',
'1138, NILESH GUPTA, 97500.0\n')
fobj.writelines(data1) #writes data1 into employee.txt
fobj.writelines(data2) #writes data2 into employee.txt
fobj.close()
fobj is the file object
'employee.txt' is the file name
'w' is the mode, 'w' stands for write mode
data1, data2 are the iterable objects (variable) containing strings

FAIPS, DPS Kuwait Page 3 / 16 ©Bikram Ally


Python Notes Class XII Text File
How to read from a text file? In Python data can be read from a text file in four ways:
• Using file object method read()
Syntax: strobj=fileobject.read()
Method read() will transfer content of an entire text file as a string into a string object
(variable). Return value of read() method is string.
fileobject is a Python object which is created with open()
strobj is the string variable/object to store the entire text file as a string
Example #1:
fobj=open('costo.txt', 'r')
data=fobj.read() #text file is stored as a string in data
fobj is the file object
'costo.txt' is the file name
'r' is the mode, 'r' stands for read mode
data is the string variable (object)
Example #2:
fobj=open('costo.txt', 'r') First 100 characters of the text
data=fobj.read(100)
file is stored as a string in data.
fobj is the file object
'costo.txt' is the file name
'r' is the mode, 'r' stands for read mode
data is the string variable (object)

• Using file object method readline()


Syntax: strobj=fileobject.readline()
Method readline() will transfer a line of text (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 text file
to a string object(variable). Return value of readline() method is string.
fileobject is a Python object which is created with open()
strobj is the string variable/object storing a line of text (string) read from a text file
Example #1: Reads a line of text (string) from a text file
fobj=open('costo.txt', 'r')
till it encounters a '\n' or end of file.
data=fobj.readline()
fobj is the file object Without any '\n' in the text file, read() and
'costo.txt' is the file name readline() will produce same result.
'r' is the mode, 'r' stands for read mode
data is the string variable (object)

• Using file object method readlines()


Syntax: strlist=fileobject.readlines()
Method readlines() will transfer entire data from a text file to a list of strings (strlist).
Method readline() returns a list (list of string(s).
fileobject is a Python object which is created with open()
strlist is the data (list of strings) to store an entire file, read from a text file, assuming
every line in the text file is terminated by '\n' and if there are no '\n' in the text file, then a
list will be created with a single string.
Example #1: Reads the entire text file as a list of
fobj=open('costo.txt', 'r') strings, if every line in the text file is
data=fr.readlines() terminated by '\n'. Number of elements
fobj is the file object in the list depends on number of lines
present in the text file.
'costo.txt' is the file name
'r' is the mode, 'r' stands for read mode
data is the list of strings
FAIPS, DPS Kuwait Page 4 / 16 ©Bikram Ally
Python Notes Class XII Text File
• Using for loop and file object as an iterator
Syntax: for line in fileobject: #process / display every line
fileobject is a Python object which is created with open()
line will represent every line of text (string) read from the text file through the
fileobject assuming every line is terminated by '\n'.
Example #1:
fobj=open('costo.txt', 'r')
for line in fobj: print(line.strip())
fobj is the file object
'costo.txt' is the file name
'r' is the mode, 'r' stands for read mode
line is a string (line of text read from the file)

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)

Running of the scripts produces following outputs:


FILE1.TXT w False
FILE2.TXT a False
DATA1.DAT ab False
DATA2.DAT rb False
FILE1.TXT w True
FILE3.TXT r True
DATA1.DAT ab True
DATA2.DAT rb True

FAIPS, DPS Kuwait Page 5 / 16 ©Bikram Ally


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

FAIPS, DPS Kuwait Page 6 / 16 ©Bikram Ally


Python Notes Class XII Text File
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 existing • If a file exists, new data will be written at the
data in the file => loss of data end of the file => no loss of data

#Edited program is given below:


fa=open('costo.txt', 'a')
s1=' Costo is part of Regency Group which is among\n'
s2=' the foremost retail players in GCC region.\n’
fa.write(s1)
fa.write(s2)
fa.close()

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

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

FAIPS, DPS Kuwait Page 7 / 16 ©Bikram Ally


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

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

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.

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.


FAIPS, DPS Kuwait Page 9 / 16 ©Bikram Ally
Python Notes Class XII Text File
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()

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

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

FAIPS, DPS Kuwait Page 16 / 16 ©Bikram Ally

You might also like