Class Xii File Handling
Class Xii File Handling
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.
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
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.
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.
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
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
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
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
L 10 Cot 4
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
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
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
RESTART : C:\Users\preeti\AppData\Local\
Is file closed : False
Is file closed now: True
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
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.