File Handling
File Handling
File handiling
For
Class – XII
KAPIL SEHGAL
KAPIL SEHGAL (P.G.T. (CS) K.V. NO2 Delhi Cantt,
Need for data file
• The data stored with in a file is known as persistent data because
this data is permanently stored in the system.
• Python provides reading and writing capability of data files.
• We save the data in the files for further use.
• As you save your data in files using word, excel etc. same thing we
can do with python.
• “A File is a collection of characters in which we can perform read and write functions. And also
we can save it in secondary storage.”
KAPIL SEHGAL
FILE TYPES
File are of two types –
1. Text File: A text file is sequence of line and line is the sequence of characters and this file is saved
in a permanent storage device. Although in python default character coding is ASCII but by using
constant „U‟ this can be converted into UNICODE. In Text File each line terminates with a special
character which is EOL (End Of Line). These are in human readable form and these can be created
using any text editor.
2. Binary File: Binary files are used to store binary data such as images, videos audio etc. Generally
numbers are stored in binary files. In binary file, there is no delimiter to end a line. Since they are
directly in the form of binary hence there is no need to translate them. That‟s why these files are
easy and fast in working.
KAPIL SEHGAL
Data File Operations
Data File Operations
1. Opening a File
2. Perform Operations (i.e. Read or Write etc.)
3. Closing the File
Beside above operations there are some more operations can be done on files.-
• Creating of Files
• Traversing of File
• Appending Data into file.
• Inserting Data into File.
• Deleting Data from File.
• Copying of File.
• KAPIL
Updating Data into File.
SEHGAL
Opening & Closing Files
• We need a file variable or file handle to work with files in Python.
• This file object can be created by using open( ) function or file( ) function.
• Open( ) function creates a file object, which is used later to access the file using the functions
related to file manipulation.
• Its syntax is following -
<file_object>=open(<file_name>,<access_mode>)
<file_object>.close()
Write to file
Python
(Save)
External
Basic operations Program
File
(Secondar
y Storage)
1. Write into File Read
2. Read From File. from file
(Load)
KAPIL SEHGAL
Simple program
KAPIL SEHGAL
Append mode
file=open("sample.txt","w")
lst=["Computer Science \n","Physics \n","Mathematics \n","Chemistry \n","Hindi \n","English \n"]
file.writelines(lst)
print("Data Write Successfully ")
file.close()
Read n methods
file=open("sample.txt","r")
data=file.read(5)
file=open("sample.txt","r") print(data, " ")
data=file.read(5) data=file.read(5)
print(data, " ") print(data, " ")
file.close() data=file.read(5)
print(data, " ")
KAPIL SEHGAL file.close()
Readline method
Readline methods read one line at a time. When file is open, by default file pointer is always at first
character of file (or first line)
KAPIL SEHGAL
Compares between read() and readlines()
Similarity
read() method and readlines() method both extract entire data from file in one go
Difference
read() method extracts entire data into a single string variable. But readlines() method extracts entire data
into form of list of string, it means each line of text file will be an element of List and in form of String.
1. read() :- Read the entire file in one go and store data into string form
2. read(n) :- Read the n characters from current location of file pointer in file. (When file is open that
time file pointer be at first position.
3. readline() :- Read the file line by line and store line into string form
4. readlines() : Read the entire file in one go and store in form of List of String i.e. One line will be
one element of list and that element in form of string.
1. write() :- Write the string into file, it takes only one string type parameter.
2. writelines() : Write the list into file, one element of string in one line.
KAPIL SEHGAL
Important programs – cbse exam based
Write a program to write five Write a program to read a file and display size of
names into file using file in bytes
writelines
Let the file “new.txt” Contains Program
file=open("new.txt","w")
lst=[] Hello Students how are you? file=open("new.txt","r")
for i in range(0,5): I hope you all are fine. data=file.read()
nm=input("Enter name ") size=len(data)
lst.append(nm+"\n") print("Size of File in Bytes ", size)
file.writelines(lst) file.close()
file.close()
Output.
Like “w” mode “x” mode also open the fresh file but unlike “w” mode, “x” mode do not overwrite file if
it is already exist but it will show run time error.
For Ex. file=open("new.txt","x")
str=input("Enter String ")
file.write(str)
Error Message file.close()
RESTART: C:\Users\Kapil\AppData\Local\Programs\Python\Python35\createfile.py
Traceback (most recent call last):
File "C:\Users\Kapil\AppData\Local\Programs\Python\Python35\createfile.py", line 1, in <module>
file=open("new.txt","x")
FileExistsError: [Errno 17] File exists: 'new.txt'
KAPIL SEHGAL
Flush method
flush() method is an inbuilt method in Python, it is used to clear/flush the internal buffer, it is best
practice while working with file handling in Python, the internal buffer can be cleared before
writing/appending the new text to the file.
Input write() flush() File
User Data R.A.M. Buffer Permanent
file.close() Storage
Without flush() With flush()
file=open("new.txt","w") file=open("new.txt","w")
str=input(“First Interruption ") str=input("First Interruption ")
file.write("one") file.write("one")
file.write("Two") file.write("Two")
st=input(“Second Interruption") file.flush()
file.write("three") st=input(“Second Interruption ")
file.close() file.write("three")
KAPIL SEHGAL file.close()
open a file through “with”
We can also open a file through “with” keyword. Using this way we don‟t need to close file.
KAPIL SEHGAL
File pointer
A file pointer is simply a marker which keeps track of the number of bytes read or written in a
file. This pointer automatically moves after every read or write operation.
When a file is opened the file pointer points at the beginning of the file. The write() function begins
writing at the current file position and then increments the file pointer. For example, the following
figure shows the position of file pointer after each write operation.
seek(offset) :- seek(offset) function moves the file pointer to the given offset from the origin
KAPIL SEHGAL
Let the file “new.txt” Contains Tell & seek method program
Hello Students how are you?
I hope you all are fine.
file=open("new.txt","r")
file=open("new.txt","r")
location=file.tell() Output data=file.read(5)
Output
print(location) print(data)
data=file.read(5) 0 data=file.read(3) Hello
print(data)
print(data) Hello St
file.seek(15)
location=file.tell() 5 data=file.read(3) how
print(location) St print(data) hop
data=file.read(3) 8 file.seek(32)
data=file.read(3)
print(data) print(data)
location=file.tell() file.close()
print(location)
KAPIL SEHGAL
Important programs
KAPIL SEHGAL
Important programs for assignment
1. Write a function to read a file called “new.txt” and count how many “the” word in it.
2. Write a function to read a file and count how many word „Do”. “Do” will be in any case
[“DO”,”do”,‟Do”,”dO”]
3. Write a function to read a file “new.txt” and copy only those lines which ends with „s‟ or “S” to
another file “new1.txt”
4. Write a program to read a file “new.txt” print number of characters in each line.
5. Write a function counteven() to read a file and count how many even number in file “new.txt”
6. Write a program to read a file and count & print only vowels store in it.
KAPIL SEHGAL
Important programs for assignment
Write a program to read a file and count & print only vowels store in it.
file=open("new.txt","r")
data=file.read()
count=0
v=[]
for i in data:
if i in ['a','e','i','o','u','A','E','I','O','U']:
if i not in v:
v.append(i)
count=count+1
file.close()
print(v)
print("Number of Vowel ",count)
KAPIL SEHGAL
Binary file
1. To handle binary file operation, we need a special library called “pickle”
7.KAPIL
Mode for Reading a binary file (Existing File ) : rb # here b indicate binary
SEHGAL
Binary file programs
Write a program to create a binary Write a program to create a binary
file using dictionary data file using list and tuple
import pickle import pickle
with open("new.dat","wb") as file: with open("new.dat","wb") as file:
s1={"name":"Ram","Class":"12C"} l1=[10,20,30,40,50]
s2={"name":"Mohan","Class":"12C"} t1=(50,60,70,80)
pickle.dump(s1,file) pickle.dump(l1,file)
pickle.dump(s2,file) pickle.dump(t1,file)
Write a program to read binary file Write a program to read a binary file
using dictionary data using list and tuple
import pickle import pickle
with open("new.dat","rb") as file: with open("new.dat","rb") as file:
d1=pickle.load(file) list=pickle.load(file)
d2=pickle.load(file) tuple=pickle.load(file)
print(d1) print(list)
print(d2)
KAPIL SEHGAL print(tuple)
Binary file programs
Create a binary file with multiple read a binary file with multiple objects
objects import pickle
mainlist=[]
import pickle with open("new.dat","rb") as file:
with open("new.dat","wb") as while True:
file: try:
l1=[10,20,30,40,50] list=pickle.load(file)
l2=[60,70,80,90,100] mainlist.append(list)
l3=[110,120] print(list)
l4=[130,140,150] except EOFError:
pickle.dump(l1,file) break
Output.
pickle.dump(l2,file) print(mainlist)
pickle.dump(l3,file) [10, 20, 30, 40, 50]
pickle.dump(l4,file) [60, 70, 80, 90, 100]
[110, 120]
[130, 140, 150]
KAPIL SEHGAL [[10, 20, 30, 40, 50], [60, 70, 80, 90, 100], [110, 120], [130, 140, 150]]
Append in binary file
w.a.p. to append a list into binary file read a binary file with multiple objects
import pickle
import pickle with open("new.dat","rb") as file:
with open("new.dat",“ab") as file: list=pickle.load(file)
l1=[110,210,310,410,510] tuple=pickle.load(file)
pickle.dump(l1,file) list1=pickle.load(file)
pickle.dump(t1,file) Read object from binary file print(list)
print(tuple)
import pickle print(list1)
with open("new.dat","rb") as file:
while True:
try:
var=pickle.load(file)
print(var)
except EOFError:
KAPIL SEHGAL break
String write read and append in binary file
Write append
import pickle
import pickle with open("new.dat","ab") as file:
with open("new.dat","wb") as file: s1="This is Vidisha"
s1="This is Mumbai" s2="This is Jhansi"
s2="This is Delhi" s3="This is Ujjain"
s3="This is Bhopal" pickle.dump(s1,file)
pickle.dump(s1,file) read
pickle.dump(s2,file)
pickle.dump(s2,file) pickle.dump(s3,file)
import pickle
pickle.dump(s3,file)
with open("new.dat","rb") as file:
while True:
try:
str=pickle.load(file)
print(str)
except EOFError:
KAPIL SEHGAL break
search in binary file
Write a program to search object in to the Write a program to search String in Binary
binary files file contains strings.
import pickle
import pickle with open("new.dat","rb") as file:
rlist=[110,210,310,410,510] # list for search str=input("Enter String to Search ")
with open("new.dat","rb") as file: flag=0
while True: while True:
try: try:
list=pickle.load(file) str1=pickle.load(file)
if (str1==str):
if (list==rlist): print ("Search Successful ")
print(list) flag=1
print("Data Found ") break
else: except EOFError:
print(list) break
except EOFError: if flag==0:
print("Search Unsuccessful")
break
KAPIL SEHGAL
Binary file programs
write a program to read a Binary file “new.dat” which contains list and tuple and find
the sum of the elements of list and tuple.
Output.
KAPIL
SumSEHGAL
of elements of list 410
Binary file programs
write a program to read a Binary file “new.dat” modify the specific oBject
create update
import pickle
import pickle record=[]
with open("new.dat","wb") as file: oldstr=input("Enter String to Replace ")
s1="This is Vidisha" newstr=input("Enter New String ")
with open("new.dat","rb+") as file:
s2="This is Jhansi" while True:
s3="This is Ujjain" try:
s4=[10,20,30,"Ram","Krishna"] read str=pickle.load(file)
record.append(str)
s5=(50,60,70) import pickle except EOFError:
s6={"Name":"Ram","Age":25} with open("new.dat","rb") as file: break
pickle.dump(s1,file) while True: count=-1
pickle.dump(s2,file) for i in record:
try: count=count+1
pickle.dump(s3,file) str=pickle.load(file) if (i==oldstr):
pickle.dump(s4,file) print(str) record[count]=newstr
pickle.dump(s5,file) except EOFError: file.seek(0)
pickle.dump(s6,file) for i in record:
KAPIL SEHGAL
break pickle.dump(i,file)
Binary file programs
write a program to read a Binary file “new.dat” modify the specific oBject
update
create import pickle
import os
import pickle oldobject="This is Vidisha"
with open("new.dat","wb") as file: newobject=["This","is","Vidisha"]
s1="This is Vidisha" tfile=open("temp.dat","wb")
s2="This is Jhansi" with open("new.dat","rb") as file:
read while True:
s3="This is Ujjain" try:
pickle.dump(s1,file) import pickle objread=pickle.load(file)
pickle.dump(s2,file) if (oldobject==objread):
with open("new.dat","rb") as file: pickle.dump(newobject,tfile)
pickle.dump(s3,file) while True: else:
try: pickle.dump(objread,tfile)
str=pickle.load(file) except EOFError:
break
print(str) tfile.close()
except EOFError: os.remove("new.dat")
KAPIL SEHGAL break os.rename("temp.dat","new.dat")
Binary file programs
write a program to read a Binary file “new.dat” delete the specific oBject
Delete
create import pickle
record=[]
import pickle t=(50,60,70)
with open("new.dat","wb") as file: with open("new.dat","rb+") as file:
s1="This is Vidisha" while True:
try:
s2="This is Jhansi" str=pickle.load(file)
s3="This is Ujjain" record.append(str)
s4=[10,20,30,"Ram","Krishna"] read except EOFError:
break
s5=(50,60,70)
import pickle count=-1
s6={"Name":"Ram","Age":25} for i in record:
with open("new.dat","rb") as file:
pickle.dump(s1,file) count=count+1
while True: if (i==t):
pickle.dump(s2,file)
try: break
pickle.dump(s3,file) del record[count]
str=pickle.load(file)
pickle.dump(s4,file) file.seek(0)
print(str) for i in record:
pickle.dump(s5,file)
except EOFError: pickle.dump(i,file)
pickle.dump(s6,file)
KAPIL SEHGAL break file.truncate()
Binary file programs
write a program to read a Binary file “new.dat” delete the specific oBject
Delete
create
import pickle
import pickle import os
with open("new.dat","wb") as file: oldobject="This is Jhansi"
s1="This is Vidisha" tfile=open("temp.dat","wb")
with open("new.dat","rb") as file:
s2="This is Jhansi"
read while True:
s3="This is Ujjain" try:
pickle.dump(s1,file) import pickle objread=pickle.load(file)
pickle.dump(s2,file) if (oldobject!=objread):
with open("new.dat","rb") as file: pickle.dump(objread,tfile)
pickle.dump(s3,file) while True: except EOFError:
try: break
str=pickle.load(file) tfile.close()
print(str) os.remove("new.dat")
except EOFError: os.rename("temp.dat","new.dat")
KAPIL SEHGAL break
c.s.v. file
A CSV is a comma-separated values file, which allows data to be saved in a tabular format. A CSV
file is a human readable text file where each line has a number of fields, separated by commas or some
other delimiter. The CSV file is opened as a text file
Output:-
writerobject=csv.writer(fileobject)
writerrow() method
writerow() method will write object row into the csv file one by one.
writerobject.writerow(row-of-object)
writerrows() method
writerows() method will write entire data object in one go into the csv file.
writerobject.writerows(data-object)
KAPIL SEHGAL
Write a program to write data into csv file
Let the file “firstcsv.txt” Using writerow() Method
Contains import csv
Name,Age list=[["Name","Age"],["Sourabh",16],["Abhishek",17],["Krishna",12],["Arnav",13]]
Sourabh,16 with open("secondcsv.csv","w") as file:
Abhishek,17 obj=csv.writer(file)
Krishna,12 for row in list:
Arnav,13 obj.writerow(row)
import csv
list=[["Name1","Age"],["Sourabh",16],["Abhishek",17],["Krishna",12],["Arnav",13]]
with open("secondcsv.csv","w") as file:
obj=csv.writer(file)
obj.writerows(list)
KAPIL SEHGAL
Methods of c.s.v. file
DictReader() method
The csv.DictReader class operates like a regular reader but maps the information read into a dictionary.
The keys for the dictionary can be passed in with the fieldnames parameter or inferred from the first
row of the CSV file.
DicReaderObject=csv.DictReader(fileobject [,fieldnames=filenamelist])
When CSV file contains heading When CSV file does not contains heading
import csv
import csv with open("secondcsv.csv","r") as file:
with open("secondcsv.csv","r") as file: colname=['Name','Age']
obj=csv.DictReader(file) obj=csv.DictReader(file,fieldnames=colname)
for row in obj: for row in obj:
print(row) print(row)
print(row["Name"],",",row["Age"]) print(row["Name"],",",row["Age"])
KAPIL SEHGAL
DictWriter() method Methods of c.s.v. file
csv.DictWriter writes the values from Python dictionaries into the CSV file.
DicWriterObject=csv.DictWriter(fileobject [,fieldnames=filenamelist])
writeheader() method
The writeheader() method writes the headers to the CSV file. For ex. object.writeheader()
import csv
with open("newcsv.csv","w") as file:
sdict={'Stname':'Krishna','Rollno':151}
colname=['Stname','Rollno']
cwriter=csv.DictWriter(file,fieldnames=colname)
cwriter.writeheader()
cwriter.writerow(sdict)
cwriter.writerow({'Stname':'Ram','Rollno':150})
KAPIL SEHGAL