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

Python File Handling and Pickle Module

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views8 pages

Python File Handling and Pickle Module

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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 [Link] 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 [Link] 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("[Link]")

File Object/File Handle:-A file object is a reference to a file on [Link] 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.
• [Link]([n]) : reads and return n bytes, if n is not specified it reads entire file.
• [Link]([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.
• [Link](): reads all lines and returns them in a list
Examples:
Let a text file “[Link]” 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\\[Link]",'r') Python is interactive language. It is case sensitive
str=[Link]( ) 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’[Link]’,’w’)
data = ‘My name is Aarav.’
[Link](data)
[Link]( )
f=open(r’[Link]’,’r’)
data = [Link]( )
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:
[Link](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:
[Link]()
Example-1: tell()function: OUTPUT:
Example: fout=open("[Link]","w") 14
[Link]("Welcome Python")
print([Link]( ))
[Link]( )

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 [Link]?
2. Aarti is new in python data-handling. Please help her to count the number of lines which begins with ‘W’ or ‘w’ in

[Link].

(a) # Line 1 : To open file [Link] 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(“[Link]”,”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:
[Link](objname, file-object )
Read the object from a file:
[Link](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
[Link](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("[Link]","wb") # open file in binary and write mode
[Link](list, file)
[Link]()

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("[Link]", "rb")
list =[Link](file)
print(list)
[Link]()
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=[Link](f)
for i in stu:
if i[1].lower()==[Link]():
rno=int(input("Enter the updated Roll number"))
s=[rno,name]
[Link](s)
else:
[Link](i)
except:
break
[Link]()
f=open("[Link]","rb+")
update()
[Link](newstu,f)
print(“Record updated”)
[Link]()
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 = [Link](fw)
found=0
lst= []
for x in list:
if roll not in x['roll']:
[Link](x)
else:
found=1
fw=open(“[Link]”,”rb+”)
delestudent()
[Link](lst,fw)
[Link]()
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 [Link] 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("[Link]","rb")
_________________ ANS. data=[Link](f1)

print(data)
[Link]()
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):
[Link](Names[i])
with open('[Link]', 'wb') as fout:
[Link](1st, fout)
with open('[Link]', 'rb') as fin:
nlist = [Link](fin)
print(nlist)

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


3. A binary file “[Link]” has structure [admission_number, Name, Percentage]. Write a function countrec()
in Python that would read contents of the file “[Link]” 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("[Link]","rb")
num = 0
try:
while True:
rec=[Link](fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
[Link]()
return num

Common questions

Powered by AI

The 'tell()' function provides the current position of the file pointer, which is essential for monitoring and controlling file access during read/write operations. For example, after writing 'Welcome Python' to a file, calling 'tell()' returns 14, indicating the byte position after the written string. This aids in data manipulation tasks requiring knowledge of the current file state .

The 'seek()' function allows the programmer to move the file pointer to a specific position within the file, enhancing control over read/write operations. By specifying an offset and a mode ('0' for the beginning, '1' for the current position, '2' for the end), it enables random access, which is crucial for processing large files or files where only specific parts need to be read or modified .

The 'flush()' function is used to force Python to write the contents of its internal buffer to the storage device. Although Python automatically flushes the buffer when a file is closed with 'close()', 'flush()' can be called before closing if immediate writing to the disk is necessary. This function is useful in applications where timely file writing is critical .

The 'open' function in Python creates a file object that facilitates reading, writing, and appending operations on files. It uses specific modes to determine the nature of these operations: 'r' or 'rb' opens the file for reading, 'w' or 'wb' opens it for writing, and 'a' or 'ab' for appending. Combined modes such as 'rb+' allow for both reading and writing, requiring the file to exist .

To update a record in a binary file using the 'pickle' module, you would typically read all records into memory, modify the specific record, and then overwrite the original file with the updated records. This involves opening the file in 'rb+' mode, reading the existing data with 'load()', modifying the record, and writing the updated data back using 'dump()' .

A new Python user can count lines in a text file starting with 'W' or 'w' by opening the file in read mode, iterating over each line while checking its first character, and counting matches. For instance, using 'readlines()' to get all lines, and a loop to verify if 'line[0].lower() == 'w'', incrementing a counter for each positive match will yield the desired count .

To delete a record from a binary file while maintaining data integrity, first load all records into memory using 'pickle.load()', identify and remove the desired record, then write the remaining records back to the file using 'pickle.dump()' after opening the file in 'rb+' mode. This approach ensures only the specified record is removed without affecting other data .

The 'pickle' module serializes Python object structures into byte streams to store them in binary files. Its methods 'dump()' and 'load()' are used for writing serialized objects to files and deserializing them back into Python objects, respectively. This allows complex data types like lists, dictionaries, and custom objects to be preserved between program executions .

Text files store data as a stream of ASCII or UNICODE characters and include end-of-line characters to separate lines, whereas binary files store data as a stream of bytes without any such line delimiters. Text files can be read in text editors whereas binary files are not readable by text editors. Examples of text files include Python script files and files created by text editors, while binary files include .exe files, mp3 files, and images .

Using specific modes while opening files in Python determines the operations permitted on the file (such as reading, writing, or appending) and affects the file's existence post-operation. For instance, 'w' mode will create or truncate a file for writing, while 'a' mode will append data to the existing file. Correct mode selection is crucial to prevent unintended data loss or errors during file manipulation .

You might also like