Text File
Text File
So far in our python program the standard input coming from keyboard
and output is going to monitor i.e no where data is stored permanently and
entered data is present as long as program is running BUT file handling
allows us to store data entered through python program permanently in
disk file and later on we can read back the data.
FILE HANDLING
DATA FILES
⮚ It contains data pertaining to a specific
application, for later use. The data files can be
stored in two ways : -
1. Text File
2. Binary File
FILE HANDLING – TEXT FILE
open() function
Syntax :
<file_objectname> = open ( < filename >) (or)
f = open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","w”)
(or)
f = open( “ student.txt”,”w”)
File Access Modes
Text file Binary file
mode mode Description
Notes
‘r’ ‘rb’ read only Default mode : File must exist already, otherwise Python raises
FileNotFoundError.
‘w’ ‘wb’ write only 🡪 If the file does not exist, file is created.
🡪 If the file exists, Python will truncate existing
data and over-write in the file. Hence this mode
must be used with caution.
‘a’ ‘ab’ Append 🡪 file is in write only mode.
🡪 If the file exists, the data in the file is retained and new data being
written will be appended to the end.
🡪 If the file does not exist, Python will create a new file.
‘r+’ ‘r+b’ or read and write 🡪 File must exist otherwise error is raised
‘rb+’ 🡪 Both reading and writing operations can take place.
‘w+’ ‘w+b’ write and read 🡪 File is created if does not exist.
or 🡪 If file exists, file is truncated ( past data is lost )
‘wb+’ 🡪 Both reading and writing operations can take place.
‘a+’ ‘a+b’ or write and read 🡪File is created if does not exist.
‘ab+’ 🡪 If file is exists, file’s existing data is retained ; new data is appended.
🡪 Both reading and writing operations can take place.
CLOSING FILES
< file handle> . close( )
The close( ) function breaks the link of file-object and the file on the disk.
After close( ), no tasks can be performed on that file through the file-
object.
Ex :
f = open(“student.txt”,”w”)
-----
-----
f.close()
Reading from text file
f=open(“student.txt”,’r’)
1. f.read( )
2. f. read(n)
3. f.readline( ) and
4. f.readlines ( )
READING FROM TEXT FILES
Right click
on the file and
select properties
The filename (student) Properties
Dialogue box will open
PATH
C:\Users\ADMIN\OneDrive\Desktop
“C:\\Users\\ADMIN\\OneDrive\\Desktop\\student1.txt",“r"
f = open(“C:\\Users\\ADMIN\\OneDrive\\Desktop\\student1.txt",“r“)
Reading from text file
f=open(“student.txt”,’r’)
1. f.read( )
2. f. read(n)
3. f.readline( ) and
4. f.readlines ( )
Reading from text file
student.txt
f=open(“student.txt”,’r’) GOOD MORNING
GOOD EVENING
GOOD AFTERNOON
1. f.read() GOOD EVENING
GOOD DAY
reads the entire content of the file byte by byte i.e character by
character
🡪 type – string
GOOD MORNING
GOOD EVENING
GOOD AFTERNOON
GOOD EVENING
GOOD DAY
Reading from text file
Coding :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r")
a=f.read()
print(a) student.txt
GOOD MORNING
f.close() GOOD EVENING
GOOD AFTERNOON
Output : GOOD EVENING
GOOD DAY
GOOD MORNING
GOOD EVENING
GOOD AFTERNOON
GOOD EVENING
GOOD DAY
Reading from text file
f=open(“student.txt”,’r’)
read( )
Coding :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r")
a=f.read() GOOD MORNING
print(len(a)) GOOD EVENING
GOOD AFTERNOON
f.close() GOOD EVENING
GOOD DAY
Output :
62
Reading from text file
f=open(“student.txt”,’r’)
GOOD EVENING
<class 'str'>
13
f=open(“student.txt”,’r’)
3. f.readline( ) 🡪 reads only one line at a time.
Coding :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r")
GOOD MORNING
a=f.readline( ) GOOD EVENING
print(a,end=‘’) GOOD AFTERNOON
b=f.readline() GOOD EVENING
GOOD DAY
print(b,end=‘’)
print(type(a))
print(len(a))
f.close()
Output :
GOOD MORNING
GOOD EVENING
<class 'str'>
13
Reading from text file
f=open(“student.txt”,’r’) GOOD MORNING
GOOD EVENING
GOOD AFTERNOON
4. f.readline(8) 🡪 Reads only 8 bytes GOOD EVENING
GOOD MOR GOOD DAY
f=open(“student.txt”,’r’)
5. f.readlines( ) 🡪 Reads the entire content of the file line by line in list
Coding : student.txt
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r") GOOD MORNING
a=f.readlines( ) GOOD EVENING
print(a) GOOD AFTERNOON
GOOD EVENING
print(type(a)) GOOD DAY
f.close( )
Output :
['GOOD MORNING\n', 'GOOD EVENING\n', 'GOOD AFTERNOON\n', 'GOOD EVENING\n',
'GOOD DAY']
<class 'list'>
student.txtx
GOOD MORNING
f=open(“student.txt”,’r’)
GOOD EVENING
GOOD AFTERNOON
5. f.readlines( ) 🡪 Reads all lines and return them in list GOOD EVENING
GOOD DAY
Coding :
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","r")
a=f.readlines( )
print(len(a))
f.close( )
Output :
5
Reading from text file
f=open(“student.txt”,’r’) student.txt
GOOD MORNING
GOOD EVENING
6. f.readlines(4) 🡪 error
GOOD AFTERNOON
GOOD EVENING
GOOD DAY
Split( ) function
>>> a="Have a nice day"
>>> b=a.split()
>>> print(b)
['Have', 'a', 'nice', 'day']
>>> print(len(b))
4
>>>
Program - 8
'''Python program to read a text file line by line and
display each word separated by a '#' '''
CODING :
file=open('C:\\Users\\user39\\Desktop\\practical1.txt','r')
lines=file.readlines()
for line in lines:
words=line.split()
for word in words :
print(word+"#",end="")
print("")
file.close()
Program - 8 - Output
SAMPLE RUN :
OUTPUT :
Like#a#joy#on#the#heart#of#a#sorrow.#
The#sunset#hangs#on#a#cloud.#
A#golden#storm#of#glittering#sheaves.#
Of#fair#and#frail#and#fluttering#leaves.#
The#wild#wind#blows#in#a#cloud.#
Program - 9
'''Python program to read a text file and display the number of vowels/consonants/ uppercase/lowercase
characters in the file'''
CODING :
file=open('C:\\Users\\user39\\Desktop\\practical1.txt','r')
content=file.read()
vowels=0
consonants=0
lower_case_letters=0
upper_case_letters=0
for ch in content:
if(ch.islower()):
lower_case_letters+=1
elif(ch.isupper()):
upper_case_letters+=1
ch=ch.lower( )
if(ch in ['a,'e','i','o','u']):
vowels+=1
if(ch in ['b','c','d','f','g','h','j','k','l','m','n',
'p','q','r','s','t','v','w','x','y','z']):
consonants+=1
Program - 9 – Continuation
file.close()
print("Vowels are:",vowels)
print("Consonants :",consonants)
print("Lower_case_letters:",lower_case_letters)
print("Upper_case_letters:",upper_case_letters)
Program - 9 Output
SAMPLE RUN :
OUTPUT :
Vowels are: 83
Consonants : 128
Lower_case_letters: 200
Upper_case_letters: 11
Program - 9
Reading from text file
f=open(“student.txt”,’r’) GOOD MORNING
1. f.read() 🡪 reads the entire content of the file byte by byte
GOOD EVENING
GOOD AFTERNOON
🡪 type - string
GOOD EVENING
GOOD MORNING
GOOD EVENING GOOD DAY
GOOD AFTERNOON
GOOD EVENING
GOOD DAY
2. f. read(6) 🡪 reads 6 bytes ( should not be given after read() function in coding ) – type - string
GOOD M
3. f.readline( ) 🡪 reads only one line at a time.
GOOD MORNING
a=f.readline( )
print(a,end="")
b=f.readline()
print(b)
4. f.readline(8) 🡪 Reads only 8 bytes
GOOD MOR
5. f.readlines( ) 🡪 Reads all lines and return them in list
['GOOD MORNING\n', 'GOOD EVENING\n', 'GOOD AFTERNOON \n‘,’GOOD EVENING\n’,’GOOD DAY\n’]
6. f.readlines(4) 🡪 error
WRITING ONTO TEXT FILES
f.close()
==== RESTART: C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\prac.py ====
Enter the name of the student : Ram
Enter the name of the student : Ravi
Enter the name of the student : Priya
Enter the name of the student : Raghul
Enter the name of the student : Rani
>>>
WRITE( ) using for loop
writelines( )- To write the all the content together
Coding 1:
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student1.txt","w")
lst = [ ]
for i in range(5):
name=input("Enter the name of the student : ")
lst.append(name+"\n")
f.writelines(lst)
f.close()
==== RESTART: C:\Users\ADMIN\AppData\Local\Programs\Python\Python39\prac.py ====
Enter the name of the student : aaa
Enter the name of the student : bbb
Enter the name of the student : ccc
Enter the name of the student : ddd
Enter the name of the student : eee
>>>
writelines ( )
Program – 10
'''Python program to remove all the lines that contain the character 'a' in a file and write it to another file '''
CODING :
file=open("C:\\Users\\user39\\Desktop\\practical1.txt","r")
lines =file.readlines()
file.close()
file=open("C:\\Users\\user39\\Desktop\\practical1.txt","w")
file1=open("C:\\Users\\user39\\Desktop\\practical2.txt","w")
for line in lines:
if 'a' in line or 'A' in line:
file1.write(line)
else:
file.write(line)
print("Lines containing char 'a' has been removed from pratical1.txt file")
print("Lines containing char 'a' has been saved in practical2.txt file")
file.close()
file1.close()
Program – 10 Output
OUTPUT :
Lines containing char 'a' has been removed from pratical1.txt file
Lines containing char 'a' has been saved in practical2.txt file
Program - 11
''' Write a python program to take a sample of ten phishing e-mails (or any text file)
and to find most commonly occurring word(s) in it.'''
CODING :
file=open("C:\\Users\\user39\\Desktop\\program12.txt","r")
content=file.read()
max=0
max_occuring_word=""
occurances_dict={}
words=content.split()
for word in words:
count=content.count(word)
occurances_dict.update({word:count})
if count>max:
max=count
max_occuring_word=word
print("Most occuring word is :", max_occuring_word)
print("No of times it occured is :",max)
print("Other words frequncy is :")
print(occurances_dict)
Program – 11 (output)
Output :
Standard Input, output and Error streams
sys module
Standard Input, output and Error streams
Coding 1:
import sys
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt“)
a=f.read() GOOD MORNING
GOOD EVENING
sys.stdout.write(a)🡪 Writes the data on the monitor GOOD AFTERNOON
GOOD EVENING
sys.stderr.write("\nNo errors Occurred\n") GOOD DAY
f.close()
import sys
f=open("C:\\Users\\ADMIN\\OneDrive\\Desktop\\student.txt","w")
a=sys.stdin.readline() 🡪 Gets the data from the user
f.write(a) 🡪 Writes the same data on the file
f.close()
Standard Input, output and Error streams
>>>
==== RESTART: C:\Users\ADMIN\AppData\Local\Programs\
Python\Python39\prac.py ====
|Have a nice day
>>>
Have a nice day
with statement
f = open (“ student.txt ” , ” r ” )
…..
f.close()
main prg report prg jan sal mar sal yr1 sal yr2 sal cashac bankac
Relative Path : The relative paths are relative to current working directory denoted as a
dot(.) while its parent directory is denoted with two dots(..)
..\cl.dat ..\proj1\report.prg
Sta
S
MCQ – FILE HANDLING - TEXT FILE
Which of the following option is not correct?
a) if we try to read a text file that does not exist, an error occurs.
b) if we try to read a text file that does not exist, the file gets created.
c) if we try to write on a text file that does not exist, no error occurs.
d) if we try to write on a text file that does not exist, the file gets Created.
MCQ – FILE HANDLING - TEXT FILE
Which of the following option is not correct?
a) if we try to read a text file that does not exist, an error occurs.
b) if we try to read a text file that does not exist, the file gets created.
c) if we try to write on a text file that does not exist, no error occurs.
d) if we try to write on a text file that does not exist, the file gets Created.
Which of the following options can be used to read the first line of a
text file Myfile.txt?
a) myfile.read()
b) myfile.read(n)
c) myfile.readline()
d) myfile.readlines()
Assume that the position of the file pointer is at the beginning of 3rd
line in a text file. Which of the following option can be used to read all
the remaining lines?
a) myfile.read()
b) myfile.read(n)
c) myfile.readline()
d) myfile.readlines()🡪 display in form of list
A text file student.txt is stored in the storage device. Identify the
correct option out of the following options to open the file in read
mode.
(i) myfile = open('student.txt','rb')
(ii) myfile = open('student.txt','w')
(iii) myfile = open('student.txt','r')
(iv) myfile = open('student.txt')
a) only i
b) both i and iv
c) both iii and iv
d) both i and iii
A text file student.txt is stored in the storage device. Identify the
correct option out of the following options to open the file in read
mode.
(i) myfile = open('student.txt','rb')
(ii) myfile = open('student.txt','w')
(iii) myfile = open('student.txt','r')
(iv) myfile = open('student.txt')
a) only i
b) both i and iv
c) both iii and iv
d) both i and iii
Suppose the content of “Essay.txt" is :-
myfile = open("Essay.txt")
line_count = 0
data = myfile.readlines()
for line in data:
if line[-2] in 'Rr':
line_count += 1
print(line_count)
myfile.close()
a) 2 b) 3 c) 4 d)5
Suppose the content of “Essay.txt" is :-
myfile = open("Essay.txt")
line_count = 0
data = myfile.readlines()
for line in data:
if line[-2] in 'Rr':
line_count += 1
print(line_count)
myfile.close()
a) 2 b) 3 c) 4 d)5
Suppose content of 'Myfile.txt' is:
a) 3 b) 4
c) 5 d) 6
Suppose content of 'Myfile.txt' is:
a) 3 b) 4
c) 5 d) 6
Suppose content of 'Myfile.txt' is
a) 24
b) 25
c) 26
d) 27
Suppose content of 'Myfile.txt' is
a) 24
b) 25
c) 26
d) 27
Suppose content of 'Myfile.txt' is
Honesty is the best policy.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
print(len(x))
myfile.close()
a) 5
b) 25
c) 26
d) 27
Suppose content of 'Myfile.txt' is
Honesty is the best policy.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
print(len(x))
myfile.close()
a) 5
b) 25
c) 26
d) 27
Consider a file “TEST.txt” contains the following: What will be there in
the file after executing the coding
TEST.txt
Good Morning
Good Afternoon
def function ( ):
fin = open (“TEST.txt”, ‘w’)
fin.write (“Good Night”)
fin.close ( )
a) Good Morning b) Good Night c) Good Morning d) Good Night
Good night Good night Good morning
Consider a file “TEST.txt” contains the following:
TEST.txt
Good Morning
Good Afternoon
def function ( ):
fin = open (“TEST.txt”, ‘w’)
fin.write (“Good Night”)
fin.close ( )
a) Good Morning b) Good Night c) Good Morning d) Good
Night
Good night Good night Good morning
Consider a file “TEST.txt” contains the following: What will be there in the file
after executing the coding
TEST.txt
Good Morning
Good Afternoon
def function ( ):
fin = open (“TEST.txt”, ‘a’)
fin.write (“Good Night”)
fin.close ( )
a) Good Morning b) Good Night c) Good Morning d) Good Night
Good Afternoon Good night Good morning
Good Night
Consider a file “TEST.txt” contains the following: What will be there in the file
after executing the coding
TEST.txt
Good Morning
Good Afternoon
def function ( ):
fin = open (“TEST.txt”, ‘a’)
fin.write (“Good Night”)
fin.close ( )
a) Good Morning b) Good Night c) Good Morning d) Good Night
Good Afternoon Good night Good morning
Good Night
Suppose content of 'Myfile.txt' is
Culture is the widening of the mind and of the spirit.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
y = x.count('the')
print(y)
myfile.close()
a) 2
b) 3
c) 4
d) 5
Suppose content of 'Myfile.txt' is
Culture is the widening of the mind and of the spirit.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
y = x.count('the')
print(y)
myfile.close()
a) 2
b) 3
c) 4
d) 5
Suppose content of 'Myfile.txt' is
a) 2 b) 3
BINARY ACADEMY c) 4 d) 5 MRS. GEETHA ROBIN M.SC.,M.PHIL.,M.ED ( COMPUTER SCIENCE )
Suppose content of 'Myfile.txt' is
Twinkle twinkle little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle twinkle little star
What will be the output of the following code?
myfile = open("Myfile.txt")
line_count = 0
data = myfile.readlines()
for line in data:
if line[0] == 'T':
line_count += 1
print(line_count)
myfile.close()
a) 2 b) 3 c) 4 d) 5
Assume the content of text file, 'student.txt' is:
Arjun Kumar
Ismail Khan
Joseph B
Hanika Kiran
What will be the data type of data_rec?
myfile = open("Myfile.txt")
data_rec = myfile.readlines()
myfile.close()
a) string
b) list
c) tuple
d) dictionary
Assume the content of text file, 'student.txt' is:
Arjun Kumar
Ismail Khan
Joseph B
Hanika Kiran
What will be the data type of data_rec?
myfile = open("Myfile.txt")
data_rec = myfile.readlines()
myfile.close()
a) string
b) list
c) tuple
d) dictionary
Consider the following directory structure
Suppose root directory (School) and present working directory are the same. What will
be the absolute path of the file Syllabus.jpg?
a) School/syllabus.jpg
b) School/Academics/syllabus.jpg
c) School/Academics/../syllabus.jpg
d) School/Examination/syllabus.jpg
Consider the following directory structure
Suppose root directory (School) and present working directory are the same. What will
be the absolute path of the file Syllabus.jpg?
a) School/syllabus.jpg
b) School/Academics/syllabus.jpg
c) School/Academics/../syllabus.jpg
d) School/Examination/syllabus.jpg