File Handling
File Handling
PYTHON
INTRODUCTION TO FILES
We have so far created programs in Python that accept the input,
manipulate it and display the output.
But that output is available only during execution of the program
and input is to be entered through the keyboard. This is because
the variables used in a program have a lifetime that lasts till the
time the program is under execution.
What if we want to store the data that were input as well as the
generated output permanently so that we can reuse it later?
Usually, organisations would want to permanently store
information about employees, inventory, sales, etc. to avoid
repetitive tasks of entering the same data.
Hence, data are stored permanently on secondary storage devices
for reusability. We store Python programs written in script mode
with a .py extension.
Each program is stored on the secondary device as a file. Likewise,
the data entered, and the output can be stored permanently into a
file
INTRODUCTION TO
FILES
• There are mainly two types of data files — text file and binary file. A text
file consists of human readable characters, which can be opened by any
text editor.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
EXAMPLE 1:
a = open("C:\\test\pritika.txt")
print(a.read())
a.close()
OPENING READING &
CLOSING FILE
EXAMPLE 2 :
a = open("C:\\test\pritika.txt","a")
a.write("New content")
a.close()
a = open("C:\\test\pritika.txt","r")
print(a.read())
WRITING TO A
TEXT FILE
• For writing to a file, we first need to open it in write or append mode.
If we open an existing file in write mode, the previous data will be
erased, and the file object will be positioned at the beginning of the
file. On the other hand, in append mode, new data will be added at
the end of the previous data as the file object is at the end of the file.
After opening the file, we can use the following methods to write
data in the file :
a = open("C:\\Pritika\Ex1.txt" , "a")
print(a.write(" goodevening"))
a.close()
a = open("C:\\Pritika\Ex1.txt" , "w")
marks = 58
#number 58 is converted to a string
using
#str()
a.write(str(marks))
a.close()
WRITING TO A
TEXT FILE
The writelines() method
This method is used to write multiple strings to a file. We need to pass an iterable object
like lists, tuple, etc. containing strings to the writelines() method. Unlike write(), the
writelines() method does not return the number of characters written in the file.
a = open("C:\\Pritika\Ex1.txt" , "w")
str = ["hello everyone \n", "how are you ?" , " I am learning python programming "]
a.writelines(str)
a.close()
To read the entire file line by line using the readline(), we can
use a loop. This process is known as looping/ iterating over a file
object. It returns an empty string when EOF is reached.
READING FROM A TEXT
FILE
•The readlines() method
•The method reads all the lines and returns the
lines along with newline as a list of strings.
a = open("C:\\Pritika\Ex1.txt" , "r")
print (a.readlines(50))
a.close()
PROGRAM TO WRITE AND READ A
TEXT FILE
This function returns an integer that specifies the current position of the file object in the file. The
position so specified is the byte position from the beginning of the file till the current position of
the file object.
This method is used to position the file object at a particular position in a file
The syntax of seek() is: file_object.seek(offset [, reference_point])
The seek() function sets the position of a file pointer and the
tell() function returns the current position of a file pointer.
SEEK ()
For example, when you open a file in write mode, the file
pointer is placed at the 0th position, i.e., at the start of the
file. However, it changes (increments) its position as you
started writing content into it.
Or, when you read a file line by line, the file pointer moves
one line at a time.
The following are the parameters that we need to pass for the
os.rename() method
import os
if os.path.isfile(new_name):
print("The file already exists")
else:
# Rename the file
os.rename(old_name, new_name)
DELETE (REMOVE) FILES AND DIRECTORIES
IN PYTHON
import os
import os
a = open("C:\\Pritika\Test.txt")
str = a.read()
size = len(str)
print("size of file is" , size , "bytes")
Ques 3
a = open("C:\\Pritika\Test.txt")
str = a.readlines()
linecount = len(str)
print("Number of lines in File is : " , linecount)
a.close()
Ques 4
count= int(input(" What is the Total Strenght of
class ? "))
a = open("C:\\Pritika\Test.txt" , 'w')
for i in range(count):
print("Enter details of student", (i+1) , "below")
rollno = int(input("Roll Number"))
name = input("Name:")
marks = float(input("Marks"))
file1 = open("C:\\Pritika\Test.txt","r")
str1 = file1.read()
vowel_count = 0
for i in str1:
if( i=='A' or i=='a' or i=='E' or i=='e' or i=='I'
or i=='i' or i=='O' or i=='o'
or i=='U' or i=='u'):
vowel_count +=1
file1.close()
BINARY FILES IN
PYTHON
Most of the files that we see in our computer system are called
binary files.
Example:
1.Document files: .pdf, .doc, .xls etc.
2.Image files: .png, .jpg, .gif, .bmp etc.
3.Video files: .mp4, .3gp, .mkv, .avi etc.
4.Audio files: .mp3, .wav, .mka, .aac etc.
5.Database files: .mdb, .accde, .frm, .sqlite etc.
6.Archive files: .zip, .rar, .iso, .7z etc.
7.Executable files: .exe, .dll, .class etc.
BINARY FILE
MODES
THE PICKLE MODULE
During execution of a program, we may require to store current state of
variables so that we can retrieve them later to its present state. Suppose
you are playing a video game, and after some time, you want to close it. So,
the program should be able to store the current state of the game, including
current level/stage, your score, etc. as a Python object. Likewise, you may
like to store a Python dictionary as an object, to be able to retrieve later. To
save any object structure along with data, Python provides a module called
Pickle. The module Pickle is used for serializing and de-serializing any
Python object structure. Pickling is a method of preserving food items by
placing them in some solution, which increases the shelf life. In other words,
it is a method to store food items for later consumption.
The pickle module deals with binary files. Here, data are not written but
dumped and similarly, data are not read but loaded. The Pickle Module must
THE DUMP() METHOD
This method is used to convert (pickling) Python objects for writing data in a binary file. The
file in which data are to be dumped, needs to be opened in binary write mode (wb).
DAT files are data files that contain information pertaining to the program that
they're associated with.
import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
fileobject.close()
THE LOAD() METHOD
import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)
FILE HANDLING USING PICKLE
MODULE
import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)
Write a program to create a list of 10
numbers and store it in a file “num.dat”
import pickle
L=[]
for i in range(10):
num = int(input("Enter number"))
L.append(num)
f=open("num.dat" , 'wb')
pickle.dump(L,f)
f.close()
#To verify your input, below is the code for
reading file
f=open("num.dat" , 'rb')
d = pickle.load(f)
print(d)
Write a program to write the following dictionary in
a binary file named “detail.dat”.
D = {1 : ‘A’, 2 : ‘B’, 3 : ‘C’}
import pickle
f=open("detail.dat" , 'wb')
pickle.dump(D,f)
f.close()
f=open("detail.dat" , 'rb')
d = pickle.load(f)
print(d)
Write a program to store roll number and marks of
five students in a dictionary and write the
dictionary in a binary file “student.dat”
import pickle
d={ }
for i in range(5):
rno = int(input("Enter Roll number"))
marks = int(input("Enter marks"))
d[rno] = marks
f=open("student.dat" , 'wb')
pickle.dump(d,f)
f.close( )
#To verify your input, below is the code for
reading file
f=open("student.dat" , 'rb')
d = pickle.load(f)
print(d)
import pickle
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
while True:
print("RECORD No.", recno)
eno=int(input("Employee number : "))
ename=input("Employee Name : ")
ebasic=int(input("Basic Salary : "))
allow=int(input("Allowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
ans=input("Do you wish to enter more records (y/n)? ")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
break
import csv
f = open(“data.csv” , ‘r’)
row = csv.DictReader(f)
for i in row:
print(i)
PROGRAMS
Q1. Write a program to read entire data from
file data.csv
import csv
f=open("data.csv", 'r')
d=csv.reader(f)
for row in d:
print(row)
Q2. Write a program to add/insert records in file “data.csv”. Structure of a record is
roll number, name and class.
import csv
f = open("data.csv" , 'w')
d=csv.writer(f)
d.writerow(field)
ch='y'
rec=[rn,nm,cls]
d.writerow(rec)
f.close()
Q. 3Write a program to copy the data from “data.csv” to
“temp.csv”
import csv
f=open("data.csv","r")
f1=open("temp.csv",'w')
d=csv.reader(f)
d1=csv.writer(f1)
for i in d:
d1.writerow(i)
f.close( )
f1.close( )
Q.4 Write a program to show the detail of the student who scored
the highest marks. Data stored
import csv
in “Data.csv” is given below
Rollno, Name, Marks
1, Aman, 35 f=open("data.csv","r")
2, Kanak, 1
3, Anuj, 33 d=csv.reader(f)
4, suman, 25
next(f)
max=0
for i in d:
if int(i[2])>max:
max=int(i[2])
f.close()
f=open("data.csv","r")
d=csv.reader(f)
next(f)
for i in d:
if int(i[2])==max:
print(i)
f.close()