CLASS XII-PYTHON-FILE HANDLING - Resource
CLASS XII-PYTHON-FILE HANDLING - Resource
CLASS XII
COMPUTER SCIENCE (083)
Chapter : Data File Handling
FILE HANDLING
WRITE
INTRODUCTION
DATA FILES
OPENING AND CLOSINGFILES
READING AND WRITING FILES
STANDARD INPUT, OUTPUT AND ERROR STREAMS
Introduction
WRITE
FILE HANDLING is a mechanism by which we can
read data of disk files in python program or write
back data from python program to disk files.
So far in our python program the standard input in
coming from keyboard an output is going to
monitor i.e. no where data is stored permanent 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
DATA FILES
WRITE It contains data pertaining to a
specific application, for later use. The
data files can be stored in two ways –
Text File
Binary File
Text File
Text file stores information in ASCII OR
WRITE UNICODE character. In text file everything will
be stored as a character for example if data is
“computer” then it will take 8 bytes and if the
data is floating value like 11237.9876 it will take 10
bytes.
In text file each line is terminated by special
character called EOL. In text file some
translation takes place when this EOL character is
read or written. In python EOL is ‘\n’ or ‘\r’ or
combination of both
Binary files
WRITE
File can be opened for either – read, write, append.
SYNTAX:
file_object = open(filename)
Or
file_object = open(filename,mode)
1. OPENING FILE
WRITE
We should first open the file for read or write by specifying the
name of file and mode.
2. PERFORMING READ/WRITE
Once the file is opened now we can either read or write for which
file is opened using various functions available.
3. CLOSING FILE
After performing operation we must close the file and release the file
for other application to use it.
Opening File
WRITE
myfile = open(“story.txt”)
myfile = open(“d:\\mydata\\poem.txt”,”r”)
here we are accessing “poem.txt” file stored in
separate location i.e. d:\mydata folder.
at the time of giving path of file we must use double
backslash(\\) in place of single backslash because in
python single slash is used for escape character and it
may cause problem like if the folder name is “nitin” and we
provide path as d:\nitin\poem.txt then in \nitin “\n” will
become escape character for new line, SO ALWAYS
USE DOUBLE BACKSLASH IN PATH
Opening File
WRITE
myfile = open(“d:\\mydata\\poem.txt”,”r”)
myfile = open(r“d:\mydata\poem.txt”,”r”)
File Handle
WRITE
myfile = open(r“d:\mydata\poem.txt”, “r”)
‘r’ ‘rb’ Read only File must exists, otherwise Python raises
I/O errors
‘w’ ‘wb’ Write only If file not exists, file is created
If file exists, python will truncate existing data and
overwrite the file.
‘a’ ‘ab’ Append File is in write mode only, new data will be added
to the end of existing data i.e. no overwriting. If file
not exists it is created
‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised Both
reading and writing can take place
w+ ‘w+b’ or ‘wb+’ Write and read File is created if not exists, if exists data will be
truncated, both read and write allowed
‘a+’ ‘a+b’ or ‘ab+’ Write and read Same as above but previous content will be
retained and both read and write.
Closing file
WRITE As reference of disk file is stored in file handle so to
close we must call the close() function through the
file handle and release the file.
myfile.close()
WRITE
output
WRITE
EXAMPLE-2:read()
Sample file
WRITE
output
WRITE
EXAMPLE-3:readline()
Sample file
WRITE
output
WRITE
WRITE
WRITE EXAMPLE-5:reading line by line using for loop
Sample file
output
WRITE
WRITE EXAMPLE-6:Calculatibg size of file with and without EOL
and blank lines.
Sample file
output
WRITE
WRITE EXAMPLE-7: readlines()
Sample file
WRITE
output
WRITE EXAMPLE- 8: Counting the size of file in bytes.
Sample file
output
WRITE
EXAMPLE- 9: Counting the no: of lines in a file.
Sample file
output
WRITE
Writing on to files
After read operation, let us take an example
of how to write data in disk files. Python
provides functions:
write ()
writelines()
The above functions are called by the file
handle to write desired content.
Now we can observe that while writing data to file using “w” mode the previous content of existing
file will be overwritten and new content will be saved.
If we want to add new data without overwriting the previous content then we should write using “a”
mode i.e. append mode.
WRITE
Example-2: write() using “a” mode
New content is
added after
previous content
WRITE
Example-3: using writelines()
WRITE
Example-4: Writing string as a record to a file
WRITE
Example-4: Writing string as a record to a file
WRITE
Example-5: To copy the content of one file to
another file
WRITE
Example-4: To copy the content of one file to
another file
Second file is created
WRITE
flush() function
When we write any data to file, python hold
everything in buffer (temporary memory) and
pushes it onto actual file later. If you want to
force Python to write the content of buffer
onto storage, you can use flush() function.
Without flush()
Nothing is in
the file
temp.txt
NOW PRESS
Without flush() ANY KEY
Nothing is in
the file
temp.txt
With flush()
All contents
before flush() are
present in file
File Pointer
Every file maintains a file pointer which tells
Nothing is in
the file
the current position in the file where readingtemp.txt
and writing operation will take.
When we perform any read/write operation
two things happens:
The operation at the current position of
file pointer
File pointer advances by the specified
number of bytes.
WRITE
Example
myfile = open(“ipl.txt”,”r”)
Nothing is in
the file
temp.txt
Nothing is in
the file
WRITE
temp.txt
Binary file operations
Nothing is in
WRITE If we want to write a structure such as list or dictionary
the file
temp.txt
to a file and read it subsequently we need to use the
Python module pickle.
Pickling is the process of converting structure to a
byte stream before writing to a file and while
reading the content of file a reverse process
called Unpickling is to convert the byte stream back
to the original format.
Steps to perform binary file operations
Nothing is in
First we need to import the module called pickle. the file
WRITE
This module provides 2 main functions: temp.txt
import pickle
f = open("student.dat","wb")
OUTPUT
ans = 'y'
WRITE Enter roll number: 101
record = [ ]
while ans == 'y‘ : Enter name: Anil
rollno = int(input("Enter roll number:")) Enter marks: 99
name = input("Enter name:") Add more(y/n): y
marks = int(input("Enter marks:")) Enter roll number: 102
data = [rollno, name, marks] Enter name: Sunil
record.append(data) Enter marks: 98
ans=input("Add more(y/n):") Add more(y/n): n
pickle.dump(record, f)
f.close()
BINARY FILE OPERATIONS
Exceptions in Python
Python has many built-in exceptions that are raised when your
program encounters an error (something in the program goes
WRITE wrong).
When these exceptions occur, the Python interpreter stops the
current process and passes it to the calling process until it is
handled. If not handled, the program will crash.
For example, let us consider a program where we have
a function A that calls function B, which in turn calls function C.
If an exception occurs in function C but is not handled in C, the
exception passes to B and then to A.
If never handled, an error message is displayed and our
program comes to a sudden unexpected halt.
BINARY FILE OPERATIONS
WRITE
Catching Exceptions in Python
In Python, exceptions can be handled using
a try statement.
The critical operation which can raise an exception is
placed inside the try clause. The code that handles
the exceptions is written in the except clause.
BINARY FILE OPERATIONS
WRITE
BINARY FILE OPERATIONS
# Reading a binary file “student.dat” and displaying the data.
import pickle
f = open(“student.dat","rb")
print("Contents of student file are:")
while True:
WRITE
try:
stud_rec = pickle.load(f)
for R in stud_rec: OUTPUT
rollno = R[0] Contents of student file are:
name = R[1] 101 Anil 99
marks = R[2] 102 Sunil 98
print(rollno,name,marks)
except EOFError :
break
f.close()
BINARY FILE OPERATIONS
# Searching for a record in the binary file “student.dat” and displaying the data.
import pickle
f = open(“student.dat","rb")
rno = int(input("Enter the roll number to search:"))
found = 0
while True:
try: OUTPUT
WRITE stud_rec = pickle.load(f)
Enter the roll number to search:101
for R in stud_rec: Successful search : 101 Anil 99
if R[0]== rno :
rollno = R[0]
name = R[1] OUTPUT
marks = R[2] Enter the roll number to search:103
print("Successful search : ", rollno, name, marks) Record not found
found = 1
except EOFError :
break
if found == 0:
print("Record not found")
f.close()
BINARY FILE OPERATIONS
seek() function
When we open a file, the system points to the beginning of the file. Any
read or write will happen from the start. To change the file object’s
position, use seek(offset, whence) function. The position will compute
WRITE by adding offset to a reference point, and the whence argument selects
the reference point. It is useful when operating over an open file. If we
want to read the file but skip the first 5 bytes, open the file, use function
seek(5) to move to where you want to start reading, and then continue
reading the file.
Description:
•Syntax: file_pointer .seek(offset, from_what).
•Offset: In seek() function, offset is required. Offset is the position of
the read/write pointer within the file.
•from_what: This is optional. It defines the point of reference. The
default is 0, which means absolute file positioning.
BINARY FILE OPERATIONS
seek() function
WRITE
BINARY FILE OPERATIONS
seek() method
Example:
WRITE
f.seek(10,0) - from beginning of file move10 bytes forward
f.seek(10,1) - from current position move 10 bytes forward
f.seek(-10,1) - from current position move 10 bytes backward
f.seek(-20,1) - from current position move 20 bytes backward
f.seek(-15,2) - from end of the file move 15 bytes backward
Note: Python 3.x only supports text file seeks from the
beginning of the file. seek() with negative offset and relative
positioning only works when the file is opened in binary mode.
BINARY FILE OPERATIONS
tell() Method
Python File tell() Method : python file can be used to return
WRITE the current position of the file object /position pointer within
the file. This method returns an integer value and takes no
parameter.
Syntax:
x= f.tell()
BINARY FILE OPERATIONS
#Updating/Modifying marks of a record in the binary file "student.dat"
import pickle
lst=[]
f = open("student.dat","rb+")
rno = int(input("Enter the roll number to search:"))
found = 0
WRITE while True :
try:
stud_rec = pickle.load(f)
for i in range(len(stud_rec)):
if stud_rec[i][0]== rno :
print("Name:", stud_rec[i][1])
print("Current mark is :", stud_rec[i][2])
stud_rec[i][2] = int(input("Enter new mark:"))
found = 1
lst.append(stud_rec)
except EOFError:
break
BINARY FILE OPERATIONS
#Updating/Modifying marks of record in the binary file "student.dat“
(continuation…)
if found == 1:
f.seek(0)
for i in range(len(lst)): OUTPUT
WRITE
pickle.dump(lst[i], f) Enter the roll number to search:100
else: Record not found!!!
print("Mark Updated!!!")
else:
print("Record not found!!!") OUTPUT
f.close() Enter the roll number to search:104
Name: Suhana
Current mark is : 90
Enter new mark:96
Mark Updated!!!
BINARY FILE OPERATIONS
How to Rename a File/Directory in Python?
Python os module offers various functions to deal and interact with
the underlying operating system of the particular device.
import os
os.remove(“student.dat”)
BINARY FILE OPERATIONS
#Deleting a record in the binary file "student.dat"
import pickle
import os
f1 = open("student.dat","rb")
f2 = open(“temp.dat","wb")
rno = int(input("Enter the roll number to delete:"))
WRITE found = 0
newlst=[]
while True :
try:
stud_rec = pickle.load(f1)
for R in stud_rec:
if R[0]== rno :
found=1
continue
newlst.append(R)
except EOFError:
break
BINARY FILE OPERATIONS
pickle.dump(newlst,f2)
f1.close()
WRITE f2.close()
os.remove("student.dat")
os.rename(“temp.dat","student.dat") OUTPUT
if found == 1:
Enter the roll number to delete:100
print("Record Deleted")
Record not found
else:
print("Record not found")
OUTPUT
Enter the roll number to delete:104
Record Deleted
MENU DRIVEN PROGRAM FOR BINARY FILES
OPERATIONS USING SEPARATE FUNCTIONS FOR
EACH FILE OPERATION.
WRITE
WRITE
WRITE
WRITE
WRITE
(Updating/Modifying program continuation……….)
WRITE
WRITE
(Deleting a record program continuation……….)
WRITE
WRITE
MENU DRIVEN PROGRAM FOR BINARY FILES
OPERATIONS USING SEPARATE FUNCTIONS FOR
EACH FILE OPERATION.
WRITE
WRITE
WRITE
WRITE
WRITE
(Updating/Modifying program continuation ………)
WRITE
WRITE
(Deleting a record program continuation ………)
WRITE
WRITE
STORY.TXT HAS THE FOLLOWING INFORMATION.
CONSIDER THIS FILE FOR THE FOLLOWING
PROGRAMS IN THE NEXT SLIDE(S).
WRITE
Q. Write a function in Python to count the number of lines
in a text file “STORY.TXT” which are starting with the
alphabet “A” or “a”.
WRITE
def countlines():
f = open("STORY.TXT","r")
lines = f.readlines() Output
count = 0 Total lines: 2
for w in lines:
if w[0] == "A" or w[0] == "a" :
count = count + 1
print("Total lines:", count)
f.close()
Q. Write a function in Python to read a text file
“STORY.TXT” and display those words which are less
than 4 characters.
def read_csv():
f = open("Marks.csv","r") # opens file in read mode
csv_r = csv.reader( f, delimiter =',') # reader() function reads the file object
for row in csv_r: # reading the Marks.csv file record by record
print(row)
f.close() OUTPUT
['Name', 'Class', 'Year', 'Percent']
[ 'Akhil', 'XII', '2005', '78']
['Sunil', 'XI', '2006', '98']
WRITE Q . Write a function search_csv() to search for a record in a
CSV file “Marks.csv” and display it.
def search_csv():
f = open("Marks.csv","r") # opens file in read mode
csv_r = csv.reader(f, delimiter =',') # reader() function reads the file object
name = input("Enter the name to be searched :")
found=0
# reading the Mark.csv file record by record
for row in csv_r: OUTPUT
if row[0]== name: Enter the name to be searched :Sunil
print(row) [‘Sunil', 'XI', '2006', '98']
found=1
OUTPUT
if found==0:
Enter the name to be searched :Sunitha
print("Record not found") Record not found
f.close()
WRITE Q . Write a function append_csv() to append records in a
CSV file “Marks.csv”.
def append_csv():
rows=[]
lst=[]
ans='y'
while ans=='y':
Name=input("Enter your name:")
Class = input("Enter the class:")
Year = input("Enter the year:")
Percent= input("Enter the percentage:")
lst=[Name,Class,Year,Percent]
rows.append(lst)
ans=input("Do you want to add more(y/n):")
WRITE
Continuation of append_csv() function……
with open("Marks.csv","a",newline='') as f:
csv_w = csv.writer( f, delimiter = ',')
for i in rows:
csv_w.writerow(i)
print("Record(s) appended") OUTPUT
Enter your name: Vimal
Enter the class: XI
Enter the year:2007
Enter the percentage:94
Do you want to add more(y/n):n
Record(s) appended
Q . Write a function modify_csv() to modify records in a CSV file “Marks.csv ”.
def modify_csv():
f= open("Marks.csv","r") # opens file in read mode
csv_r = csv.reader(f, delimiter=',') # reader() function reads the file object
name = input("Enter the name to be searched :")
found=0
lst=[ ]
for row in csv_r: # reading the Marks.csv file record by record
if row[0]== name:
row[1] = input("Enter the new class:")
row[2] = input("Enter the new year:")
row[3] = input("Enter the new percentage:")
found=1
print(“Record Modified”)
lst.append(row)
Continuation of modify_csv() function……….
f.close()
with open("Marks.csv","w", newline =‘ ') as f:
csv_w = csv.writer(f, delimiter=',')
for i in lst: OUTPUT
csv_w.writerow(i) Enter the name to be searched :Sunil
Enter the new class: XI
if found==0: Enter the new year: 2008
print("Record not found") Enter the new percentage:99
Record Modified
OUTPUT
Enter the name to be searched : Abhilash
Record not found
Q . Write a function delete_csv() to delete a record in a CSV file “Marks.csv ”.
def delete_csv():
f1= open("Marks.csv","r") # opens Marks.csv file in read mode
f2= open("Temp.csv","w",newline=‘ ') # opens Temp.csv file in write mode
csv_r = csv.reader(f1,delimiter=',') # reader() function reads the file object
csv_w = csv.writer(f2,delimiter=',')
found=0
name=input("Enter the name to be deleted :")
for row in csv_r: # reading the Marks.csv file record by record
if row[0]== name:
found=1
print("Record Deleted")
continue
csv_w.writerow(row)
Continuation of delete_csv() function……….
f1.close()
f2.close()
os.remove("Marks.csv")
os.rename("Temp.csv","Marks.csv")
if found==0: OUTPUT
Enter the name to be deleted :Sunil
print("Record not found") Record Deleted
OUTPUT
Enter the name to be deleted : Subash
Record not found