XII - Computer science
3. FILE HANDLING
[ TEXT FILE
] SHAHIDA A. BACKER
Files
➢ Files itself is a bunch of bytes stored on some storage device like hard
disk, thumb drive etc.
➢ Files are used to store the information permanently.
➢ Files will work inside the program.
SHAHIDA A. BACKER
Data Files
The data files are the files that store data pertaining to a specific application, for
later use.
Data files can be stored in two ways:
1.Text Files
2.Binary Files
SHAHIDA A. BACKER 3
TEXT FILES
Text file stores information in ASCII or Unicode characters.
In text file, each character is terminated with a special character known as EOL .
EOL - End of line.
By default EOL is new line character(‘\n’)
Internal translations will takes place when this EOL character is read or written.
SHAHIDA A. BACKER 4
BINARY FILES
It is a file that store information in the form of a stream of bytes.
It contains information in the same format in which the information is held in the memory.
There is no delimiter for a line.
No translations will occur in binary files.
Binary files are more faster and easier for a program to read and written than text files.
It is the best way to store program information.
SHAHIDA A. BACKER 5
FILE OPERATIONS:
Opening a file
Adding data to the files.(Writing)
Reading data from the files
Appending data to the files.
Modifying data from the files.
Deleting data from the files.
Closing a file
SHAHIDA A. BACKER 6
Need for file?
To store the data permanently.
Stores data in the secondary memory.
So, that we can use data any time.
SHAHIDA A. BACKER
FILE MODES:
The default file open mode is read.
•If file mode is not provide the Python will open it in read mode.
•A file mode governs the type of operations possible in the opened file.
•It refers to how the file will be used once it is opened.
SHAHIDA A. BACKER
TEXT FILE BINARY FILE DESCRIPTION NOTES
MODE MODE
‘r’ ‘rb’ Read only File must exist already, otherwise Python
raises I/O error.
‘w’ ‘wb’ Write only •File is in write only mode.
•If the file exists the Python will truncate
the existing data and overwrite in the file
•If the file does not exist, Python will
create a new a file.
‘a’ ‘ab’ append •File is in write only mode.
•If the file exists, the data in the file is
retained and new data will be appended to
the end
•If the file does not exist, Python will
create a new a file.
SHAHIDA A. BACKER 9
TEXT FILE BINARY FILE DESCRIPTION NOTES
MODE MODE
‘r+’ ‘r+b’ or ‘rb+’ Read and Write •File must exist already, otherwise Python
raises I/O error.
•Both reading and writing operations can
takes place.
‘w+’ ‘w+b ‘ or ‘wb+’ Write and Read •File is created if does not exist.
•If the file exists, file is truncated.
•Both reading and writing operations can
takes place.
‘a+’ ‘a+b’ or ‘ab+’ Write and Read •File is created if does not exist.
•If the file exists, the data in the file is
retained and new data will be appended to the
end.
•Both reading and writing operations can
takes place. SHAHIDA A. BACKER 10
STEPS IN FILE HANDLING PROCESS:
1.Open a file: It indicates the
purpose of
opening the file
Syntax:
fileobject=open(“filename”, “filemode”)
A File-object is also
Eg: f=open(“abc.txt”,”r”) known as File-Handle
f=open(“abc.txt”)
By default file will be open in default mode(read mode ). SHAHIDA A. BACKER 11
open( ) function of Python:
f= open(“c:\\temp\\data.txt”, ‘r’)
The slashes in the path are doubled because the slashes have special meaning and to
suppress that special meaning-escape sequence-\\ is given.
To write with single slash, we write in raw string as:
f= open(r“c:\temp\data.txt”, ‘r’)
Raw string: •The prefix r in front of a string that means there is no special
meaning attached to any character.
SHAHIDA A. BACKER 12
File Object/ File HAndle
A file object is a reference to a file on disk. It opens and make available for a
number of different tasks.
A file object is a reference to a file on a disk.
•It opens and makes it available for a number of different tasks.
•It is also known as file handle or file object.
•When file open() is used , Python stores the reference of mentioned file in the
file object.
•A file object is a stream of bytes where the data can be read either byte by byte or
line by line collectively.
SHAHIDA A. BACKER 13
abc.txt
Pgm1.py
Varun
Maya
f=open(“abc.txt”) Anu
Kabir
Output screen will be
Output Screen
blank because there
is no print statement.
SHAHIDA A. BACKER 14
abc.txt
Pgm1.py
Varun
Maya
f=open(r “F:\Hello\abc.txt”) Anu
Kabir
Output screen will be
Output Screen blank because there
is no print statement.
SHAHIDA A. BACKER 15
2. Read from the file:
Syntax:
Variable=Fileobject.read( )
Variable=Fileobject.read( byte)
Variable=Fileobject.readline( )
Variable=Fileobject.readline(byte )
Variable=Fileobject.readlines( )
SHAHIDA A. BACKER 16
METHOD SYNTAX DESCRIPTION
read() Filehandle.read(n) •Read at most bytes if no n is specified,
reads the entire file.
•Reads the bytes in the form of a string.
readline() Filehandle.readline( ) •Reads a line of input if n is specified, reads
at most n bytes.
readlines() Filehandle.readlines ( ) •Reads all lines and returns them in a list.
SHAHIDA A. BACKER 17
abc.txt
Pgm1.py
Varun
f=open(“abc.txt”) Maya
a=f.read() Anu
print(a) Kabir
Output Screen
Varun
Maya
Anu
Kabir
SHAHIDA A. BACKER 18
abc.txt
Pgm1.py
Varun
f=open(“abc.txt”) Maya
a=f.read(10) Anu
print(a) Kabir
Output Screen
Varun
Maya
SHAHIDA A. BACKER 19
abc.txt
Pgm1.py
Varun
f=open(“abc.txt”) Maya
a=f.readline() Anu
print(a) Kabir
Output Screen
Varun
SHAHIDA A. BACKER 20
abc.txt
Pgm1.py
Varun
Maya
Anu
Kabir
Output Screen
Var
SHAHIDA A. BACKER 21
abc.txt
Pgm1.py
Varun
f=open(“abc.txt”) Maya
a=f.readlines() Anu
print(a) Kabir
Output Screen
[ ‘Varun\n’, ‘ Maya\n’, ‘Anu\n’, ‘Kabir\n’ ]
SHAHIDA A. BACKER 22
2. Write to the file:
Syntax:
Fileobject.write(“values”)
Fileobject.write(Variables)
SHAHIDA A. BACKER 23
METHOD SYNTAX DESCRIPTION
write() Filehandle.write(L ) •Write strings in to the file referenced by
the file object.
writelines Filehandle.writelines(L ) •Write all strings in the list to the file
referenced by the file object.
SHAHIDA A. BACKER 24
hai.txt
Pgm1.py
Hello
f=open(“hai.txt”, ‘w’)
f.write(“Hello”)
f.close()
Output screen will be
Output Screen blank because there
is no print statement.
SHAHIDA A. BACKER 25
hai.txt
Pgm1.py
***
f=open(“hai.txt”, ‘w’)
f.write(“***”)
f.close()
Output Screen
Output screen will be
blank because there
is no print statement.
SHAHIDA A. BACKER 26
hai.txt
Pgm1.py
***Hello
f=open(“hai.txt”, ‘a’)
f.write(“Hello”)
f.close()
Output Screen
Output screen will be
blank because there
is no print statement.
SHAHIDA A. BACKER 27
hai.txt
Pgm1.py
Karan
f=open(“hai.txt”, ‘w’)
a=input(“Enter the name:”)
f.write(a)
f.close()
Output Screen
Enter the name: Karan
SHAHIDA A. BACKER 28
2. Write to the file:
Syntax:
Fileobject.write(“values”)
Fileobject.write(variable)
Fileobject.writelines(“values”)
Fileobject.writelines(variable)
SHAHIDA A. BACKER 29
hai.txt
Pgm1.py
Arun
f=open(“hai.txt”, ‘w’) Maya
L=[“Arun\n”, “Maya\n”, “Joe\n”] Joe
f.writelines(L)
f.close()
Output Screen
SHAHIDA A. BACKER 30
Pgm1.py
f=open(“hai.txt”, ‘w’)
a=[ ]
n=int() input(“No. Of elements to be stored in the list:”)
for i in range(n):
b= input(“Enter the name:”)
a.append(b+’\n’)
f.writelines(a) hai.txt
f.close()
Maya
Arun
Output Screen Varun
No. Of elements to be stored in the
list: 3
Enter the name:Maya
Enter the name:Arun
Enter the name:Varun
SHAHIDA A. BACKER 31
3. Close file:
•A close() 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.
Syntax:
Fileobject.close( )
Eg: f.close( )
SHAHIDA A. BACKER 32
FileNotFoundError
FileNotFoundError occurs when we try to open a file that does not exist
in the folder.
SHAHIDA A. BACKER 33
Write a function to read and display content of a text file “poem.txt”.
def fun( ):
f=open(“poem.txt”, “r”)
s=f.read( )
print(s)
f.close( )
SHAHIDA A. BACKER
Write a function to display the content of the text file “para.txt “
in the form of a list.
sadfda
sfdsaf
def fun(): dsdfdf
f=open(“para.txt”, “r”)
s=f.readlines( )
print(s)
f.close( )
SHAHIDA A. BACKER 35
Write a function to read and display the content of the text file
“poem.txt” character by character.
0 1 2 3 4 5 6
def fun( ): S a b c 1 2 3 #
f=open(“poem.txt”, “r”) len=7
s=f.read( )
for i in range(len(s)):
print(s[i])
f.close( )
SHAHIDA A. BACKER 36
Write a function to count number of characters present in the file para.txt.
def fun():
f=open(“para.txt”, “r”) abc123#
s=f.read()
print(len(s))
f.close() def fun(): p
f=open(“para.txt”, “r”)
s=f.read()
count=0
for i in range len((s)):
count=count+1
print(count )
f.close( ) SHAHIDA A. BACKER 37
Write a function to display all the digits present in the file “story.txt”
a1b2c3defgh
def fun():
f=open(“story.txt”, “r”)
s=f.read( ) 11
for i in range(len(s)): 7
if s[i].isdigit():
O/P
print(s[i]) 1
f.close() 2
3
SHAHIDA A. BACKER 38
Write a function to display all the sum of digits present in the file “book.txt”.
def fun(): 12ab34
f=open(“book.txt”, “r”)
s=f.read( )
sum=0
for i in range(len(s)): 5
if s[i].isdigit():
11 sum=sum+s[i]
print(sum)
f.close()
SHAHIDA A. BACKER
H. W
Write a function to display all lowercase letters present in the file
“notes.txt “
def fun():
f=open(“notes.txt”, “r”)
s=f.read( )
for i in range(len(s)):
if s[i].islower():
print(s[i] )
f.close()
SHAHIDA A. BACKER 40
Polina Raj has used a text editing software to type some text in an article. After saving thearticle
as MYNOTES.TXT. After saving the article she has wrongly typed alphabet K inplace of C
everywhere in the article. Write a function definition for PURETEXT() in Python that would
display the corrected version of the entire article of the file MYNOTES.TXT with all the
alphabets K to be displayed as an alphabet C on the screen.
Note: Assuming that MYNOTES.TXT does not contain any C alphabet
Example: If the file contains
I OWN A KUTE LITTLE KAT def PURETEXT():
The function should display the following content f=open(“ MYNOTES.TXT ”, “r”)
IOWN A CUTE LITTLE CAT s=f.read()
for i in range(len(s)):
if s[i]=='K':
print("C",end='')
else:
print(s[i],end='')
f.close()
SHAHIDA A. BACKER 41
Write a function to read content of a text file “poem.txt” line by line.
def fun( ):
f=open(“poem.txt”, “r”)
s=f.readline( )
while s:
print(s)
s=f.readline()
f.close( )
SHAHIDA A. BACKER 42
Write a function to display all the lines that begins with ‘P’ from the file notes.txt
def fun( ):
f=open(“notes.txt”, “r”)
s=f.readline( )
while s:
if s[0]==”P”
print(s)
s=f.readline()
f.close( )
SHAHIDA A. BACKER 43
Write a function to display all the lines that begins with either ‘I’ or ‘ M’ from the
file notes.txt
def fun( ):
f=open(“notes.txt”, “r”)
s=f.readline( )
while s:
if s[0]==”I” or s[0]==” M”:
print(s)
s=f.readline()
f.close( )
SHAHIDA A. BACKER
Write a function to count the number of lines present in the file “novel.txt”
def fun( ):
count=0
f=open(“novel.txt”, “r”)
s=f.readline( )
while s:
count+=1 //count=count+1
s=f.readline()
f.close( )
SHAHIDA A. BACKER 45
Write a function to read the content from the file “reports/txt” The function
should display the number of lines having the word “for” present in it.
def fun( ):
count=0
f=open(“report.txt”, “r”)
s=f.readline( )
while s:
if “for” in s:
count+=1
s=f.readline()
print(count )
f.close( )
SHAHIDA A. BACKER 46
Write a function to display all the words present in the file novel.txt
def fun( ):
f=open(“novel.txt”, “r”) s=”India is my country”
s=f.read( ) r=”India” “ is” “my” “ country”
r=s.split()
for i in r:
print(i)
f.close()
SHAHIDA A. BACKER 47
H. W
Write a function to count the number of words present in the file “story.txt”.
def fun( ):
f=open(“story.txt”, “r”)
s=f.read( ) s “This is a pen”
r=s.split()
print(len(r)) r “This”, “is”, “a”, “pen”
f.close()
SHAHIDA A. BACKER 48
H. W
Write a function to count the words that begins with “n” present in the file books.txt
def fun( ):
count=0
f=open(“book.txt”, “r”)
s=f.read( ) s- “This is my notebook”
r=s.split() r- “This”, “is”,” my”, “notebook”
for i in r:
if i[0]==’n’:
count=count+1
print(count )
f.close()
SHAHIDA A. BACKER
H. W
Write a function to print the words that begins with “i” in reverse order from the
file para.txt
def fun( ): S- “india is my country”
f=open(“para.txt”, “r”) r- “india”,” is”, “my”, “country”
s=f.read( )
r=s.split()
for i in r:
if i[0]==’i’:
print(i[ : :-1])
f.close()
SHAHIDA A. BACKER 50
H. W
Write a function to count the word “hello” present in the the file “para.txt”.
def fun( ):
count=0
f=open(“para.txt”, “r”)
s=f.read( )
r=s.split()
for i in r:
if i==’hello’:
count=count+1
print(count )
f.close()
SHAHIDA A. BACKER 51
H. W
Write a function to display all the words that have 4 characters present in the file
marks.txt
def fun( ):
f=open(“marks.txt”, “r”)
s=f.read( )
r=s.split()
for i in r:
if len(i)==4:
print(i)
f.close()
SHAHIDA A. BACKER 52
Write a function to write ‘n’ number of strings to the file “para.txt”.
Arun
def fun(): ben
f=open(“para.txt”, ”w”)
n=int(input(“Enter the number of strings to be stored:”))
for i in range(n):
value=input(“Enter the string:”)
f.write(value)
f.close()
SHAHIDA A. BACKER 53
Write a function to write a list of values to the file “story.txt”.
def fun():
a=[arun\n ]
f=open(“story.txt”, ”w”)
n=int(input(“Enter the number of values to be stored in the list:”))
for i in range(n):
name=input(“Enter the name:”)
a.append(name+”\n”)
f.writelines(a)
f.close()
SHAHIDA A. BACKER
Write a function to copy all the data from the “file1.txt” to “file2.txt”.
def fun():
f1=open("file1.txt","r")
f2=open("file1.txt","w")
s=f1.read()
f2.write(s)
f1.close()
f2.close()
SHAHIDA A. BACKER 55
Write a function to copy all the lines from the file1.txt to file2.txt
def fun():
f1=open("file1.txt","r")
f2=open("file2.txt","w")
for i in f1:
f2.write(i)
f1.close()
f2.close()
SHAHIDA A. BACKER 56
Write a function to copy all the words from the file1.txt to file2.txt
def fun():
f1=open("file1.txt","r")
f2=open("file2.txt","w")
s=f.read
r=s.split
for i in r:
f2.write(i)
f1.close()
f2.close()
SHAHIDA A. BACKER 57
Write a function to copy numbers from “poem.txt” to “para.txt”.
def fun():
f1=open("poem.txt","r")
f2=open("para.txt","w")
s=f1.read()
for i in range(len(s)):
if s[i].isdigit:
f2.write(s[i])
f1.close()
f2.close()
SHAHIDA A. BACKER 58
H. W
1. Write a function to write 3 letter words from novel.txt to “word.txt”.
2. Write a function to copy all the line begins with ‘s’ from the file “abc.txt” to
“story.txt”.
3. Write a function to read all the 4 letter words from the file “words.txt” and
copy it in the reverse form to the file “para.txt”.
4. Write a function that copies a text file “source.txt” onto “target.txt” barring
the starlines ting with a “@”sign.
5. Write a function that read all the lines that do not begins with lowercase
letter from the file “oldfile.txt” and copy to the file “newfile.txt”.
6. Write a function to display the longest line from the file “story.txt”.
SHAHIDA A. BACKER
SHAHIDA A. BACKER