0% found this document useful (0 votes)
22 views8 pages

Class XII Python File handling Notes5

The document provides comprehensive notes on file handling in Python, detailing the types of files (text and binary), methods for opening, reading, writing, and manipulating files, as well as the use of the pickle module for object serialization. It includes explanations of various file access modes, functions like read(), write(), flush(), seek(), and tell(), and examples of reading and writing text and binary files. Additionally, it covers practical applications such as updating and deleting records in binary files.

Uploaded by

Khushi Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
22 views8 pages

Class XII Python File handling Notes5

The document provides comprehensive notes on file handling in Python, detailing the types of files (text and binary), methods for opening, reading, writing, and manipulating files, as well as the use of the pickle module for object serialization. It includes explanations of various file access modes, functions like read(), write(), flush(), seek(), and tell(), and examples of reading and writing text and binary files. Additionally, it covers practical applications such as updating and deleting records in binary files.

Uploaded by

Khushi Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 8

Class XII Python Notes

(FILE HANDLING)
Files are of bytes stored on storage devices such as hard-disks. Files help in storing information permanently on a
computer.
Data Files:
Data files are files that store data pertaining to a specific application. The data files can be stored in following ways:
• Text files: These files store information in the form of a stream of ASCII or UNICODE characters. Each line is
terminated by an EOL character. Python programs, contents written in text editors are some of the example of text files.
• Binary files: These files store information in the form of a stream of bytes. No EOL character is used and binary files
hold information in the same format in which it is held in the memory. The .exe files, mp3 file, image files, word
documents are some of the examples of binary files.We can’t read a binary file using a text editor.

Opening Files :
To perform file operation, it must be opened first then after reading, writing,editing operation can be performed.To create
any new file then too it must be opened. On opening of any file, a file relevant structure is created in memory as well as
memory space is created to store contents. Once we are done working with the file, we should close the file.
Itisdoneusing open() function as per one of the following syntax:
<fileobjectname>=open(<filename>)
<fileobjectname>=open(<filename>,<mode>)
For example:
stu=open("students.txt")

File Object/File Handle:-A file object is a reference to a file on disk.It opens and makes it available for a number of
different tasks.
FileAccessModes:-
Text file mode Binary File Description
Mode
‘r’ ‘rb’ Read-Default value. Opens a file for reading, error if the file does not exist.
‘w’ ‘wb’ Write- Opens a file for writing, creates the file if it does not exist
‘a’ ‘ab’ Append- Opens a file for appending, creates the file if it does not exist
‘r+’ ‘rb+’ Read and Write- File must exist, otherwise error is raised.

Reading from Text Files


Python provides three types of read functions to read from a data file.
• Filehandle.read([n]) : reads and return n bytes, if n is not specified it reads entire file.
• Filehandle.readline([n]) : reads a line of input. If n is specified reads at most n bytes. Read bytes in the form of string
ending with line character or blank string if no more bytes are left for reading.
• Filehandle.readlines(): reads all lines and returns them in a list
Examples:
Let a text file “Book.txt” has the following text:
“Python is interactive language. It is case sensitive language.
It makes the difference between uppercase and lowercase letters. It is official language of
google.” Example-1:Programusingread()function: OUTPUT:
fin=open("D:\\pythonprograms\\Book.txt",'r') Python is interactive language. It is case sensitive
str=fin.read( ) language.
It makes the difference between uppercase and

Writing onto Text Files:


Like reading functions , the writing functions also work on open files.
• <filehandle>.write(str1): Wrties string str1 to file referenced by <file handle>.
• <filehandle>.writelines(L): Wrties all strings in list L as lines to file referenced by <file handle>.

E.g. MyFile
I am Peter.
How are you?
I am Peter.
How are you? OUTPUT:
Example-1:Program using write()function: My name is Aarav.
f=open(r’MyFile.txt’,’w’)
data = ‘My name is Aarav.’
f.write(data)
f.close( )
f=open(r’MyFile.txt’,’r’)
data = f.read( )
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.
• Python automatically flushes the files when closing them i.e. it will be implicitly called by the

close(), but if you want to flush before closing any file you can use flush()
seek( ) function:
The seek( ) function allows us to change the position of the file pointer in the opened file as follows:
f.seek(offset,mode)
where
offset - is a number specifying number of bytes.
mode - specifies the reference point from where the offset will be calculated to place the file pointer. The mode argument
is optional and has three possible values namely 0, 1 and 2. The default value of mode is 0.
0 - beginning of file
1 - current position in file
2 - end of file
tell( ) function:
The tell() method returns the current position of the file pointer in the opened file. It is used as follows:
f.tell()
Example-1: tell()function: OUTPUT:
Example: fout=open("story.txt","w") 14
fout.write("Welcome Python")
print(fout.tell( ))
fout.close( )

2. What does the <readlines()> method returns?


(a) Str (b) A list of lines(c) List of single
characters(d) List of integers
WORKSHEET

(a) Which line in the above code check for capital letter?
(b) Which line in the above code read the file “story. txt”?
(c) Which line in the above code does not affect the execution of program?
(d) Which line is the above code coverts capital letter to small letter?
(e) Which line is the above code opens the file in write mode?
(f) Which line is the above code saves the data?
(g) Which line(s) is/are the part of selection statement.
(h) Which line(s) is/are used to close story1.txt?
2. Aarti is new in python data-handling. Please help her to count the number of lines which begins with ‘W’ or ‘w’ in

poem.txt.

(a) # Line 1 : To open file POEM.txt in read mode


(b) # Line 2 : To check first character of every line is ‘W’ or ‘w’.
(c) # Line 3 : To increase the value of count by 1.
(d) # Line 4 : To call the function count_poem.
BINARY FILES

Binary files store data in the binary format (0’s and 1’s) which is understandable by the machine. So when we open the
binary file in our machine, it decodes the data and displays in a human-readable format.
There are three basic modes of a binary file:
• read: This mode is written as rb
• write: This mode is written as wb
• append: This mode is written as ab

The plus symbol followed by file mode is used to perform multiple operations together. For example, rb+ is used for
reading the opening file for reading and writing. The cursor position is at the beginning when + symbol is written with file
mode.
To open a binary file follow this syntax:
• file = open(<filepath>, mode) For example: f = open(“one.dat”,”rb”)
Binary File Modes: File mode governs the Description
type of operations read/write/append possible
in the opened file. It refers to how the file will
be used once its opened. File Mode
rb Read Only: Opens existing file for read
operation
wb Write Only: Opens file for write operation. If
file does not exist, file is created. If file exists,
it overwrites data.
ab Append: Opens file in write mode. If file exist,
data will be appended at the end.
rb+ Read and Write: File should exist, Both read
and write operations can be performed.
wb+ Write and Read: File created if not exist, If file
exist, file is truncated.
ab+ Write and Read: File created if does not exist,
If file exist data is truncated.

Pickle Module: Python pickle is used to serialize and deserialize a python object structure. Any object on python can be
pickled so that it can be saved on disk.

Pickling: Pickling is the process whereby a Python object hierarchy is converted into a byte stream. It is also known as
serialization

Unpickling: A byte stream is converted into object hierarchy.


To use the pickling methods in a program, we have to import pickle module using import keyword.

Example:
import pickle
In this module,we shall discuss two functions of pickle module, which are:
i) dump():To store/write the object data to the file.
ii) load():To read the object data from a file and returns the object data.

Syntax:
Write the object to the file:
pickle.dump(objname, file-object )
Read the object from a file:
pickle.load(file-object)
Write data to a Binary File:
Example:
import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname=input("Enter student Name:")
student={"roll":roll,"name":sname} # create a dictionary
list.append(student) #add the dictionary as an element in the list
choice=input("Want to add more record(y/n):")
if(choice=='n'):
break
file=open("student.dat","wb") # open file in binary and write mode
pickle.dump(list, file)
file.close()

OUTPUT:
Enter student Roll No: 1201
Enter student Name: Anil
Want to add more record(y/n): y
Enter student Roll No: 1202
Enter student Name: Sunil
Want to add more record(y/n): n
Read data from a Binary File:
To read the data from a binary file, we have to use load() function
Example:
import pickle
file = open("student.dat", "rb")
list =pickle.load(file)
print(list)
file.close()
OUTPUT:
[{'roll':'1201','name':'Anil'},{'roll':'1202','name':'Sunil'}]

Update a record in Binary File:


def update():
name=input("Enter the name to be updated ")
newstu=[]
while True:
try:
stu=p.load(f)
for i in stu:
if i[1].lower()==name.lower():
rno=int(input("Enter the updated Roll number"))
s=[rno,name]
newstu.append(s)
else:
newstu.append(i)
except:
break
f.close()
f=open("student.dat","rb+")
update()
p.dump(newstu,f)
print(“Record updated”)
f.close()
OUTPUT:
Enter the name to be updated Sunil
Enter the updated Roll number 1204
Record updated 88

Delete a record from binary file:


import pickle
def deletestudent():
roll=input('Enter roll number whose record you want to delete:')
list = pickle.load(fw)
found=0
lst= []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found=1
fw=open(“student.dat”,”rb+”)
delestudent()
pickle.dump(lst,fw)
fw.close()
if found==1:
print(“Record Deleted”)
else:
print(“Record not found”)
OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted
WORKSHEET
1. Ranjani is working on the sports.dat file but she is confused about how to read data from the binary file.
Suggest a suitable line for her to fulfil her wish.

import pickle
def sports_read():
f1 = open("sports.dat","rb")
_________________ ANS. data=pickle.load(f1)

print(data)
f1.close()
sports_read()

2. What will be displayed by the following code ?


import pickle
Names = ['First', 'second', 'third', 'fourth', 'Fifth']
for i in range(-1, -5, -1):
lst.append(Names[i])
with open('test.dat', 'wb') as fout:
pickle.dump(1st, fout)
with open('test.dat', 'rb') as fin:
nlist = pickle.load(fin)
print(nlist)

Ans- ['Fifth', 'fourth', 'third', 'second"]


3. A binary file “STUDENT.DAT” has structure [admission_number, Name, Percentage]. Write a function countrec()
in Python that would read contents of the file “STUDENT.DAT” and display the details of those students whose
percentage is above 75. Also display number of students scoring above 75%

ANS.
import pickle
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num

You might also like