0% found this document useful (0 votes)
95 views14 pages

Class Xii File Handling

all file handling imp points covver and questions

Uploaded by

mk8860649461
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views14 pages

Class Xii File Handling

all file handling imp points covver and questions

Uploaded by

mk8860649461
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

4.

2 WHY USE FILES


LData used in variables is temporary in nature.
Once the application is closed, all the variables Write to file
and data is lost. So, there comes the concept (Save)
Your
of files; in order to save our data on some
Python
secondary storage device, we have to use files. Program File allows us to
Data maintained inside the files is termed as access 'stored' data
even after we close
persistent data, i.e., it is permanent in nature. External File our programs
Python allows us to read data from and save data
to external text files permanently on secondary Read from (secondary
storage media, as shown in Fig. 4.2. Apart from file (Load) storage)
this, we permanently store the program data as
Python scripts (with .py extension) also. Fig. 4.2: Purpose of Using a File

Data is stored using file(s) permanently on secondary storage media. We usually use the files
to store data permanently while working and storing data in Word processing applications,
spreadsheets, presentation applications, etc. All of these operations require data to be stored in
files so that it may be used later.

Thus, files provide a means of communication between the program and the outside world.
In a nutshell, a file is a stream of bytes, comprising data of interest.
CTM: Afile (or data file) is astream or sequence of characters/data occupying named place on the disk
where a sequence of related data is stored. It contains data pertaining to aspecific application for later use.

l4.3 DATA FILE OPERATIONS


Before we start working with a file, first we need to open it. After performing the desirable
operation, it needs to be closed so that resources that are tied with the file are freed.
Thus, Python file handling takes place in the following order (Fig. 4.3):
1. Opening a file.
2. Performing operations (read, write, Open Process Close
append, insert, delete, etc.) or File Data File

Processing Data
Fig. 4.3: Basic File Operations
3. Closing the file.
On the basis of the given basic operations,we can process file in several ways, such as:
Creating a file
Traversing a file for displaying data on screen
Appending data in a file
Inserting datain afile
Deleting data from a file +
Creating a copy of a file
Updating data in a file ]
In this chapter, we shall be restricting ourselves to three major file operations, viz. reading,
writingand appending to the file. Rest of the
operations are beyond the scope of the syllabus.
(File Types
discuss these file
Before we operations, we should be aware of the file every
file as a collection of Os and 1s, i.e., in binary form. Therefore, types.
every file Computers
is basically just store
a series of
bvtes stored one after the other. Python allows us to create and manage three types of files:
Text file
Binary file
CSV file
BIN

txt
10110 CSV
01001

Text Flle Binary FIle CSV File

Fig. 4.4: Types of Files in Python

1. Text Files: A text file consists of asequence of lines. A line is a sequence of characters
(ASCII or UNICODE) which usually comprises alphabets, numbers and other special
symbols stored on permanent storage nedia. Text file stores information in the form of
ASCIlor UNICODE character.}Although default character coding in Python is ASCII, using
the constant 'u' with string, it supports Unicode as well. In a text file, each line is terminated
by a special character, known as End of Line (EOL). By default, this EOL character is the
newline character (\n). So, at the lowest level, text file will be acollection of bytes. In
text file, some translation takes place when this EOL character is read or written. Text files
are stored as a sequence of bytes in human-readable form and can be created using any
text editor.
We use text files to store character data. For example, test.txt.
Other examples of text files are:
" Document Files: such as .txt, .rtf, .pdf
Tabular Files: such as .cSV, .tsV
Source Code Files: such as .py, js, .C, .app, java
json
Web Standard Files: such as .html, .xml, .css,
Configuration Files: such as .ini, .cfg, .reg
2. Binary Files: Binary files are used to store binary data such asimages, video files, audio files,
etc. Abinary file contains arbitrary binary data, usually numbers stored in the file which can
be used for numerical operation(s). So, when we work on a binary file, we have to interpret
the raw bit pattern(s) read from the file into correct type of data in our program.7
Inbinary file, there is no delimiter for a line. Also, no character translations can be carried
out in a binarv file. As a result, binary files are easier and much faster than text files for
Carrying out reading and writing operations on data.
numeric
stream of bytes originally written as string as
It isperfectly possible to interpret a
interpretation of data and we may not get the
desired
incorrect of a
value. But that will be an
value after the file processing activity. So, in the case
output or might get some garbage interpret the correct data type while
reading the
that we
binary file, it is extremely important encoding and decoding of data for binary file.
special module(s) for
file. Python provides
of human-readable characters which can be opened by any text editor
Thus, atext file consists characters and symbols
up of non-human readable
On the other hand, binary files are made
access their content.
which require specific programs to
CSV stands for comma-separated values. CSV is just like a text file, i.e., it is in human
3. CSVFiles: the form of rows and columnsl
readable format, used to store data in tabular form (in
character of CSV files is called a delimiter
like a spreadsheet or a database. The separator
can be used with CSV files are
Its default delimiter is comma (). Other delimiters which
tab (\t), colon (:), pipe () and semicolon (;).
Some salient features of CSV files are:
Each record consists of fields separated by comma (delimiter).
" It isthe most preferred import and export format for databases and spreadsheets.
" Each line in a CSV file is treated as a record.

4.4 OPENING AND CLOSING FILES


To handle data files in Python, we need to have afile variable or file object or file handle. It is the
object that gets associated with a particular file to perform read/write operations at a particular
time.

Object can be created by using open() function. Towork on afile, thefirst thing we do is open
it. Thisis done by using the built-in function open(). Using this function, a file object is created
which is then used for accessing various methods and functions available for file manipulation.
A4.1 open( Opening a File
open) is the most extensively used function for handling (A variable we use to refer to
files in Python. When we want to read or write a file Your
the opened file)
Python Known as the fille handle
(say on the hard drive), we must first open the file. Program
Opening the file communicates with the operatingsystem,
which knows where the data for each file is stored. When
we open a file, we are asking the operating system to find External File
the file by name and make sure the file exists.
Read from file (secondary
open() function takes the name of the file as the first storage)
(Load/Open)
argument. The second argument indicates the mode of
accessing the file. The syntax for open() is: Fig. 4.5: Opening a File
Syntax:
<file variable>/<file object or handle> = open (file name, access mode)
Here, the first argument with open() is the name of the file to be opened and the second argument
describes the mode, i.e., how the file will be used throughout the program. This is an optional
parameter as the default mode is the read mode (reading).
and
in the other situation in which the file does not exist, open() willfail with a trace back
NOW,
of the file, as shown in the example gjven belowr.
we will not get ahandle to access the contents
Example 2: yhon 3.65 Shell
Help
Rle Edt Shel Debug Options Window
2018, 16:07:46)
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28
on win32
(MSC v.1900 32 bit (Intel)) for more inf
Type copyright", "credits" or "license () "
ormation.
>>> f open{'test. txt')
Tracelback (most recent call last):
File " <pyshell#0>", line 1, in <mOdule>
f open ('test.txt')
FileNotFoundError: [Errno 2] No such file or directory:
test. txt!

Ln:8 Co: 4

File Modes

The second parameter of the open() function correspondsto a mode which is either read ('r).
write ('w)., or append ('a). The file mode defines how the file willbe accessed. In Python, files
are opened in text mode by default. Toopen file in binary mode,it should be suffixed with 'b' to
represent binary files.
Table 4.1 explains the different modes available with both text and binary files.
Table 4.1: File Modes
Mode Description
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode. If the specified file does not exist, it will generate FileNotFoundError.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the
file. This is the default mode.
Opensa file for both readingand writing.(+) The file pointer will be at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer will be at the beginning
of the file.
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, it
a new file for writing.
creates
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.
W+ Opens afile for both writing and reading. Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writingand reading in binary format.
exists. If the file does not exist, creates a new file for readingOverwrites
and writing.
the existing file if the file
opens a ile for appending. The file pointer is at the end of the file if the file exists. That is, the file
is in the append mode. If the file does not exist, it
creates a new file for writing.
opens a file for appending in binary format. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a
a+ new file for writing.
Opens a file for both appending and reading. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for
and writing. reading
ab+
Opens a file for both appending arnd reading in binary format. The file
tile if the file exists. The file opens in the append mode. If the file doespointer
is at the end of the
not exist, it creates a new
file for reading and writing.
POINT TO REMEMBER,
The default file-open mode iS read mode. If you do not
read mode (""). provide any file-open mode, Python will open t n

Example 3:
>>> file = open("test.txt", "r+")
willopen the file test.txt for reading and writing
purpose. Here, the name (by which it exists on
secondary storage media) of the file specified is constant.
We can use avariable instead of aconstant as name of the
file, test file; if it already exists,
then it has to be in the same folder where we are working now,
otherwise we have to specity
the complete path. It is not mandatory to have file name with extension. In the
above example,
txt extension is used for our convenience of identification as it is easy to identify the file as
a
text file. Similarly, for binary file we will use .dat extension.

4.4.2 close(-Closinga File


The close() method of afile object flushes any unwritten information and closes the file object, after
which no more writing can be done. Python automatically closes a file when the reference object
of a fle is reassigned to another file. It is a good practice to use the close() method to close a file.7
Syntax:
fileobject.close ()
A close() function breaks the link between file object and the file on the disk.
After closing a file (using close()), no tasks can be performed on that file through the file object.
Example 4:
f open (' test.txt')
print ("The name of the file to be closed is:",f.name)
The name of the file to be closed is: test.txt
f.close ()
L 29 Cot 4

In the above example, we have used 'name' property of the file object F along with print()
statement, which will return the name of the currently used file, which is 'test.txt' in this case.
The above program can be alternatively performed in case the file is not present in the Python
root directory.
Let us assume that the text file is present in the D:\ drive. Then, the open) method shall be
defined as follows:
FChecking for an existing file other than Python root directory
I*open ("D:\\test.txt", "r") #accessing file with double slash if stored on
Some other drive

Print (f.read()) #read () is used for reading the data present in the file
NOTe: A file always gets opened in read mode and as text file by default.
properties of ile Object.
Let us discuss these
Various properties of File Object: created, we can retrieve
various details related to
and file object gets
Once open()is successful
properties.
that file using its associated
opened file.
1. name: Name of the
gets opened.
2. mode: Mode in which the file
indicates whether the file is closed or not
3. closed: returns Boolean value, which
returns the encoding format of the file. (Microsoft Windows 0S uses 'cn12
4. encoding:
encoding system bydefault.)
po Tielpy Cusers/preetVAppData/Local/Programs.
Window Help
Fle Edit Fomat Run Options
f-open("test, txt", 'r')
print("File Name: ",f.name)
print ("File Mode: ",f.mode)
print ("File Encoding: ",f.encoding)
print ("Is File closed: ",f.closed) Python 3.6.5 Shell
f.close () File Edit Shell Debug Options Window Help
print ("Is File closed: ",f.closed) RESTART : C:/Users/preeti/AppData/Local/Progr ams/
Python/Python36-32/prog_filel .py
File Name: test.txt
File Mode:
File Encoding: cp1252
Is File closed: False
Is File closed: True

L: 10 Co: 4

4.5 READING FROM AFILE


Python provides various methods associated with a file object for reading data from a file. We
can read character data from text file by using the following read methods:
a) read(): To read the entire data from the file; starts reading from the cursor (from the beginning
of the file)up tothe end of the file.
b) read(n): To read 'n' characters from the file, starting from the cursor; if the file holds fewer
than »n' characters, it willread until the end of the file. Also, if the size is missing or has a
negative value,then the entire file is read.
c) readline(): To read only one line from the file; starts reading from the cursor up to, and
including, the end of line character.
d) readlines(): To read all lines from the file into alist;starts reading from the cursor up to the
end of the file and returns a list of strings, separated by new line character \n.
Let us understand these methods with the help of suitable examples using a text file 'test.txt.
1) read(0/read(size): read() can be used to read entire data while read (size) can be used to
read specific-size strings from a file. This function also returns a string read from the file.
At the end of the file, again an empty string will be returned.
Syntax of read() function is:
fileobject.read() or
fileobject.read ([size])
Here, size specifies the number of bytes to be read from the file. So. the function may be used to
read a specific number of characters from the file. If the value of size is not
value is specified as size, then the entire file will be read. One must take provided
or a negatIve
care of the memory Size
available before reading the entire content from the file.
Practical Implementation-1
To illustrate read([0 function by reading the entire data from a file
(test.txt).
test.bxt-Notepad
File Edit Format View Help
Hello User
you are working with
Python
Files

prog file2.py -
File Edt Format C/Users/preeti/AppData/Mocal/Programs/Python/Pytho
Run Options Window Help
|f open ("test.txt", 'r) #Opening file in read mode A
data = f.read()
print (data)
f.close () Python 3,5.5 Shell
File Edie Shell Debug Options Window Help

RESTART: C:/Users/preeti/AppData/Local/ Programs


/Python/Python36-32/prog_file2.py
Hello User
you are working with
Python
Files
>>>

Le9 Cot 4

Practical Implementation-2
To illustrate read(n) by reading only the first 10 characters from the file (test.txt).
prog_fite3.py-c/Users/preeti/AppData/Local/Programs/P
File Edit Format Run Options Window Help
#Program to read only first 10 characters
f =open ("test.txt", 'r')
data wf.read (10)
print (data)
f.close ()
>>>
RESTART: C:/Users/preeti/AppData/Local/Programs
/Python/Python36-32/prog_file3.py
Hello User
>>>
Lne 12 Cot 4

2)( readline(): readline() function will return aline read, as a string from the file. First call
to function will return the first line, second call return the next line, and so on, We must
remember that file object keeps track from where reading/writing of data should happen.
For readline(); a líne is terminated by "n' (i.e., new line character). The new line character
is also read from the file and post-fixed in the string. When end of file is reached, readline()
will return an empty string. The syntax for readline() is:
Syntax:
fileObject.readl ine() 7
returned and stored using a variable as shown below
Since the method returns a string, it should be
>>> x = file.readline ()
or

>>> print (file.readline ())


entire file using readline(), we will have to loop over the file object. This is a
For reading an
reading the file, like:
memory efficient, simple and fast way of
>>> for line in x:
print (line)

Practical Implementation-3
To read data line by line using readline() method.
Uben/preeti/AppData/ Local/Programs/Pyhon/Py
Fle Edt Fonat Run Optlons Wndow Help
#Program to read data line by line from the file
f open ("test.txt", r')
1ine1 f.readline ()
print (1inel,end=!')
line2 =f.readline ()
Python 3.6.5 Shel
print (line2, end=') File Edit Shell Debug Options Window Help
line3 =f.readline () RESTART : C:/Users/preet1/AppData/Local/Programs
print (1ine3, end=) /Python/Python36-32/prog_f1le4 .py
line4 f.readline () Hello User
print (1ine4, end=) you are working with
f.close ()
Python
Files

Lre9 Cok 4

3) readlines(): readlines() function can be used to read the entire content of the file. This method
will print allthe lines present in the file. It will start reading the data line-wise from the
beginning of the file and shall display the contents of the file till the end of file character.
We need to be careful while using it with respect to the size of memory required before using
the function. The method willreturn alist of strings, each separated by new line character \n:
The syntax is:
Syntax:
fileobject.readl ines ()
as it returns a list, which can then be úsed for manipulation.
Practical Implementation-4
To read all the lines from the file into list.
spreti/AppData/localPrograms/Phon/Python36-32/pr
File Edit foamat Fun Options Window Help
$Prograa to read al1 1ine8 into a list (using readlines () )
f =open ("test.txt",r*)
lines =t,readlines () >>>
for 1ine ín línes:
print (0íne,end=) RESTART: C:/Users/preeti/AppData/Local/Programs/ Pyth
f.close () on/ Python36-32/prog_file5.py
Hello User
you are working with
Python
Piles

Lnt 9 Cok 4
Practical Implementation-5
Program to display the contents of the file starting from 3rd
(Modification of Practical index character into the list.
Implementation-4).
NSDy CUSeVpreet/AppDataAoca/Progranython/iythona.
Fie Édk format Run Optlons Window Halo
Rnaram to read data frOm 3Td
character into à liat. A

f =open ("test.txt", 'r') Python 365 Shell


print (. read (2)) le tdit Shel Dabug
Optlon Wndow Halp
print (f.readlines () )
print (f.read (3) ) RsSTART: C:/0sers/preeti/AppData/Local/Proqrams /Python/Pythón36
print ("Remaining data")
print (f.read () )
-32/prog_tile6.pPY
He

T"lo User\n', 'you are working with\n',


'Python\n', 'Files']

L 10 Cot 4

j4.6 WRITING TO FILE


We can write character data into a file in Python by
using the Python Hello

following two file object methods: Write File


Fta

1. write(string) Your
Python
2. writelines(sequence of lines) Program Write to
1. write(string): write(string) method takes a external file
string
(as parameter) and writes it in the text file in a single
line. For storing data with end of line character, we will
have to add \n' character to the end of the string. Notice External File

the addition of \n' at the end of every sentence while


(secondary
talking of data.txt (\n' is treated as special characters storage)
of 2 bytes). As argument to the function has to be string,
for storing numericvalue, we have to convert it to string. Fig. 4.7: Writing a File
Syntax:
fileObject.write (string)
The write() method actually writes data onto a buffer. When the close() method is executed.
the contents from this buffer are moved to the file located on the
permanent storage.
Practical Implementation-6
Program to write data to the file 'test2.txt'.
Uprog file&.py -CUsers/preeti/AppData/Locai/Programs/Pytho.
File Edit Formet Run Options Window Help
#Program to write data to a file

f-open ("test2. txt","w")


f.write ("We are writing \n")
f.write (" data to a\n")
f.write ("text file \n")
print ("Data written to the file successfully")
f.close () Python 36S Shel
File Edit Shel Debug Optiens Window Help

RESTART: C:/0sers/preeti/AppData/Local/Programs/Pyt
hon/Python36-32/prog_tile8 .py
Data written to the file successfully

Ln:ó Cok 4
The content of the file will be:
X
fnew.bt - CAUsers\ User2\AppData\LocaN Programs\Python\Pyt.
File Edit Format Run Options Window Help

Number1 :55
Number 2 :77
Sum of two numbers:132
Ln: 9 Col: 1

is used for
In the above program +' operator will concatenate the two strings and str() method
type conversion from an integer to a string.
2. writelines():For writing astring at a time, we use write() method; it can't be used for writing
a list, tuple, etc., intoa file. Sequence data type such as list, tuple, etc., including multiple
strings can be written at the same time using writelines() method in the text file.
Syntax:
fileObject.writelines (sequence)
So, whenever we have to write a sequence of string/data type, we must use writelines()
instead of write(). writelines) method accepts any type of sequence as an argument.
Practical Implementation-8
Program to add list items to a file using writelines() method.
prog_file10.py C/Users/preeti/AppData/local/Programs/Python/Python36-32/prog fi
File Edit Fomat Run Options Window Melp
#Program to illustrate Writelines () method
#for wIiting list into the file
f =open ("test4.txt", 'w')
list =[" Computer Science\n", "Physics\n", "chemistry\n","Maths"]
f.writelines (list)
print ("List of lines written to the file success full y")
f.close ()
>>>
RESTART: C:/Users/preeti/AppData/Local/Programs/Pyt
hon/Python36-32/prog.filel0.py
List of lines written to the file successfully
>>>

Ln:6 Cok 4

Contents of text file 'test4.txt':

test4.bt Notepad
File Edit Format View Help
Computer Science
Physics
Chemistry
Maths

CTM: While reading from or writing to the file, the cursor always starts from the beginning of the file.
the end
noted here is that writelines(0 method does not add any EOL character to
Also to be used \n' new line
string. We have to do it ourselves. So, to resolve this problem, we have
of
character (in the program) after the end of each list item or string.

CTM:
writelines() method accepts any type of sequence as an argument. "Mn" is explicitly passed to
writelines().

You must
have noticed that till now we have used close() method in all the programs to close
thefile in
the end. In case you don't want to close your file explicitly using close(), there is an
alternative statement which can be used in the program, i.e., 'with' statement which we wil
discuss now.

with Statement
Anart from using open(r function for creation of file, with statement can also be used for the
same purpose. We can use this statement to group file operation statements within block to
make the code compact and much more readable. This method is quite handy when you have two
related operations which you would like toexecute as a pair, with blocks of codes in between.
lUsing with ensures that allthe resources allocated to the file objects get deallocated automatically
once we stopusing the file. In the case of exceptions also, we are not required to close the file
explicitly using with statement. Itssyntax is:
Syntax:
with open ("filename", "mode") as fileObject:
file manipulation statements

Practical Implementation-9
Program to illustrate 'with' statement.
prog_file7.py CAUsers\preetiAppData\llocal\Progra
File Edit Format Rån Options Window Help
#Program to illustrate with! statement

with open ("testl.text", "w") as f:


t.write (" Python \n")
t.write ("is an easy \n")
t.write ("language \n")
t.write ("to work with \n")
print ("Is file closed : ",l.closed)
print ("Is file closed now: ",l.closed)

RESTART : C:\Users\preeti\AppData\Local\
Is file closed : False
Is file closed now: True

ontents of text file "test1.txt":


testt.text Notepad
File Edit Format View Help
Pyhon
is an sy
lenguege
to work with
<
Thus, the advantages of using with statement are:
generally are: End
L. lt handles all the exceptions occurring before the end of the block (which
of the file error and stack underflow).
file.
2. It automatically closes the file and releases the resources allocated to the
Therefore, based on the concepts learnt so far, certain important points should be kept in mind
while working with files in Python.
POINTS TO REMEMBER
1. For storing datawith EOL character, we have to add a newline (\n) at the end of every sentence to mark
the end of line.
2. In case of storing numeric value, we have to either convert it into astring using str() method or write
it in quotes.
3. We cannot write numeric data directly into the file.
4. If we don't use the close) method, it will not write anything into the file as without closing the file, the
resources are not released.
5. If we write more data toan existing file, it willoverwrite the previous data. Thus, the entire file willbe
overwritten. Therefore, in order to add datato already existing data, append mode is to be used ("a").

4.7APPENDING TO FILE
Append means 'to add to'; so if we want to add more data to a file which already has some data
in it, we will be appending data. In such a case, use the access mode 'a, which means:
'Open for writing, and if it exists, then append data to the end of the file:
In Python, we can use the 'a' mode to open an output file in append mode. This means that:
If the file already exists, it willnot be erased.
If the file does not exist, it will be created.
When data is written to the file, it willbe written at the end of the file's current contents.
Syntax:
<file _object> =open (<filename>,'a')
Here, 'a' stands for append mode, which allows to add data to the end of existing data instead of
overwriting in the file.
For example,
>>> f = open ("test1.txt", "a")

Practical Implementation--10
Program to add data to an existing file.
z prog.appfilei.2y-CNser/preeti/AppData/Local/Programs/Python/Python36
File Edit Format Run Options Window Help
#Program to add data to existing data in the file
=open (" test. txt", 'a') #opening file in append mode
L.write ("Simple syntax of the language \n")
I.write ("makes Python programs easy to read and write")
print (" More Data appended to the file")
L.close ()
Ln:& Cot 0
Hep
Gile Edit Format View
Python is an object oriented language.it is a"dynamicalytyped language. varisblein Pyhonis an object
need to declare variables before using them. Or declare their type.Every
You do not
types of numbers - integers and foatin point umbers.
Python supportstwo understanding.
Python is simple in syntax and

output, the contents of the target file show that the first character of
As is cvident from the above case(if in lower case).
the character following a full stop have been changed to upper
each line and
OPERATIONs
r4.10BINARY FILE
are called binary files.
Most of the files that we see in our computer system
Example:
Document files: .pdf, .doc, .xls,etc.
Image files: png, .jpg, gif, .bmp, etc.
Video files: .mp4,.3gp, .mk, .avi, etc.
Windows
Audio files: .mp3, .wav, .mka, .aac, etc. Binry

Database files: .mdb, .accde, .frm, .sqlite, etc. Test

Archive files: .zip, .rar, .iso, .7z, etc.


Executable files:.exe, .dll, .class, etc.
text.editor but
files follow a specific format. We can open some binary files in the normal
All binary because all the binary files are encoded in
content present inside the file. This is
we cannot read the
binary format, which can be understood only by a computer or a machine.
the
no delimiter to enda line. Since they are directly in the form of binary,
In binary files, there is and fast.
That is why these files are easy to work with
hence there is no need to translate them.

(4.10.1 Reading and Writing Datafrom/into Binary File subsequently,


wish to write a structure such as a list or dictionary to a binary file and read it
If we
We need to use the Python module pickle. structure.
module Pickle is used for serializing and de-serializing any Python object
Ihe stream
or an object n memory (RAM) to a
Derlalization is the process of transforming data or
streams. These byte streams in a binary file can then be stored in a disk
O oytes called byte Serialization process is also called pickling. Pickling
ma database or sent through a network.
converting the structure to a byte stream before writing to the file. While
elers to the process of convert the byte
contents of the file, a reverse process called Unpickling is used to
auing the
sream back to the original structure.J
writing/reading a file work with string
We know that the methods provided in Python for conversion
to work on a binary file, of data at the time of reading
parameters. So, required. Pickle module can be used to store any kind of object in a binary
as well as
when we want

file as it writingus to store Python objects with their structure.


is So, for storing data in binary
allows The following steps are
to be taken for performing reading
format, we Will use pickle module.
and writing operations on a binary file:
.11 RANDOM ACCESS IN FILES USING TELL) AND SEEK()
Till now, in all our programs we laid stress on the sequential processing of data in a text ana
binary file. But files in Python allow random access of the data as wellusing built-in methods seek()
and tell().

seek()-seek() function is used to change the position of the file handle (file pointer) to agiven
specific p0sition. File pointer is like a cursor, which defines from where the data has to be read
or written in the file.)
Python file method seek() sets the file's current position at the offset. This argument is optional
and defaults to 0, which means absolute file positioning. Other values are: 1, which signifies seek is
relative (may change) to the current position, and 2, which means seek is relative tothe end of file.
There is no return value.

The reference point is defined by the "from_ what" argument. It can have any of the three values:
0: sets the reference point at the beginning of the file, which is by default.
1: sets the reference point at the current file position.
2: sets the reference point at the end of the file position.
seek() can be done in two ways:
Absolute Positioning
Relative Positioning
Absolute referencing using seek() gives the file number on which the file pointer has to position
itself. The syntax for seek() is
f.seek (file location) #where f is the file pointer
For example, f.seek(20) will give the position or file number where the file pointer has been placed.
This statement shall move the file pointer to 20th byte in the file no matter where you are.
Relative referencing/positioning has two arguments, offset and the position from which it has to
traverse. The syntax for relative referencing is:
f.seek (offset, from what) #where f is file pointer

For example,
f.seek(-10,1) from current position, move 10bytes backward
I.seek(10,1) from current position, move 10 bytes forward
I.seek(-20,1)from current position, move 20 bytes backward
iseek(10,0) from beginning of file, move 10 bytes forward
tell()-tel) returns the current position of the file read/write pointer within the file. If we have
moved our file pointer through seek(), tel() is used to tellthe position where file pointer is currently
pointing to.
Its syntax is:
f.tell) #where f is file pointer
When you open a file in reading/writing mode, the file pointer rests at 0th byte.
When you open a file in append mode, the file pointer rests at the last byte.

You might also like