Class XII Python File handling Notes5
Class XII Python File handling Notes5
(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.
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( )
(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.
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
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'}]
import pickle
def sports_read():
f1 = open("sports.dat","rb")
_________________ ANS. data=pickle.load(f1)
print(data)
f1.close()
sports_read()
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