File Handling
File Handling
.
cours sotnee
NT] ae 5 EONS
ile Pointer in File Handling
5.4.5. Significance of File Pointer in 5, standard Input 0 ut and Error Streams
5!
‘Every file maintains a file pointer which tells the current position in the Fle where yaa
sding wl tuk place (Ale pointer in his contest wos ke a Book mac ing pane sraemeone asks Ou t0 give input fo «PTA intra o y egy ay
what
Whenever you read something from the file or write onto a fil, then these fi things re you need for it ~ the Keyboard. Similarly, if someone
involving Se pointer: EE det You kn which device i wl bedpned en demon ea =
eR ine Keyboard is the standard input device and the monitor i cn sally say
(0 this operation takes place atthe position of file pointer and
(i) fepointer advances by the specified number of bytes |
Figure 5.6 illustrates this process. Iti important to understand how a
{file pointer works in Python files. The working of file-pointer has been
described in Fig. 56. _
1. hs open (Marks. txt")
‘open te fe apace te fener atthe beginnng of he fle (se below)
Senta, any error if occurs is also displayed onthe monitor Soe mnie sah
esror device. =
‘g standard input device (stdin) - reads from the keyboard
standard output device (stdout) ~ prints tothe display and canbe
= ‘ec s andand
«9 standard error device (stderr) Same as stdout but normally only or eros Having enor
‘output separately allows the usero divert regular output ioaleandatlbe oe ea
‘error messages.
‘Do you know interally how these devices are implemented in Python? These andad devi:
pe mplemented as files called standard stream. In Pytho, you an use hese sundrd san,
files by using sys module. After importing, you can use these standard reams tdi sdoat
nd stdert in the same way as you use other files.
Ineresting : Standard Input, Output Devices os Files
If you import sys module in your program then, sysstdinread() would let you red fram
keyboard. This is because the Keyboard isthe standard input device linked to ysstdin Sarl,
sysstdout.write() would let you write on the standard output device, He mont. spastin and
sysstdout are standard input and standard output devices respectively treated as fs.
alu] [a] e[s]-[sf>[-[oTs pola [s [i Ti Ly
[rarer ineener anne
(Now the ment read will sake j place atthe current postion of file- pointer. a
swrite(Line2)
sre write(*No errors occurred\n")
fi
5.4.5A File Modes ond the Opening Posit
‘The position of a fle-pointer is governed by the flemode ed in, Following table]
‘opening position ofa fle-pointer as per filemode. oem oe
Tobie 5.4 File modes ond opening postion of fe-ponter el
[re modes we
Wwe work, we try to be better
No errors occurred *—— Ser sder abo dep! a =coger 5 PLE HANDUNG
Now the directory BACKUP'S path will be :
ts very handy when you have wo related operaions wig :\SALESYEARLY\BACRUP
in betwee. The yt fr sing Wh statemen ‘As to reach BACKUP the sequence one has to follow is : under drive E, under root directory
(Gist \), under SALES subdirectory of root, under YEARLY bes
BACKUP directory. 1 subdirectory of SALES, there
‘similarly full name of ONE.VBP file under PROP subdirectory will be:
:\ PROJECT\PROZZ\ONE. VEE
+ Parnnane
refers to
root directory
2 sequence of directory names which give you the hierarchy to acces a pag, and CASH.ACT;’s path will be df Sy
Sy nae Le cert avin deo suc “ial ahha viestieebithcr' Sr ciocen! —
foe oe
ao
eo ary
Seen
[Above mentioned pth names are Absolute Patinames as they whe te pret arecery
intone pte tom he op mot el of dinctry Sree
Beats pthc eto pt mats to Some
‘which means under current working folder, there is fle
‘TWOPAS. Similarly, path name for fle CLDAT will be
Pique 5.
Now the
meaner ger sat nccunts te esNCLADAT & (PROB being working Foden
ECT, EZASALES. and E:\act (CLDAT bn pore oder
0 format of pth canbe sven, COUNTS respectively. owen tn tet?) which mein nd rear oie ks te es
_ nor SSCL Ste ee a
here fet \ (back ooo rectory...]
the previous one. 10 r00t directory and other (’\’s) separate: a direca binary fle wil et rated when opened in an output file mode and it doesnot {
ger 5 FE HANDUNG
our
That is, for the file modes, “w’, “w+”, “a, the fle will get created if t does
file exists already, then the file modes “w" and “w+” will overwrite
“a” will retain the contents ofthe file.
‘An open binary files closed in the same manner as you close any other fle, Le, as
pedle.close()
Let us now learn to work with pickle module’s methods to writefread into binary files.
pe COMPUTER scence
1M
4
5.6 Working with Binary Files
write
cence eh
i iia orm when aE
iy
re of Ping where» byte seas i overt
ing th 4
6 anling ng produce the exact replica Othe original eea |
these methods (eading inside ty . except blocks and using with
Python provides the pile module ‘when we talk about reading fom binary files in section 863
Python's documentation, “The pic
5.62 Writing onto Binary File - Pickling
‘esericng a Python object \
‘shal lam tous pickle module for reading/writing objects in
binary fils. t
Inorder to work with the pickle
In order to write an object on to a binary file opened in the write mode, you should use dump( )
per the following syntax
-be-uritten>, «file handle-of-open-File> )
you have a file open in handle filet and you want to write alist namely fist] in
sn you may write
-dump(14St2, #161) oj un write on fle pel i fl ha Pet
* In the same way, you may write dictionaries, tuples oF any
Inport pickle module ciher Python objet in binary file using dump) function
(pen binary il inthe required fle mode (read mode or write mode) tea dictionary namely student ina file Praca alowsyouto pee bec
(2) Process binary file by wrting/reading objects using pickle module’s methods. 2 you may write : swe atone a es
ipa " meee
eet a
eng secs ig a ce os moter
int stadt i big wrinenon ements, and case bles ete
561 Creoing/Opening/Closing Binary Files [Reopened th leh as Ped
A i.
sn fe Sabian the same way as you open any other file (a explained insti __ Now consider some example programs given below.
“ : vith file modes to open a file in binary mode cs, 5.8 Wite a program to a binary fe called emp at and write ino it he employee deals of some
TOPOM SEGRE oe) af ga in mk fl employees, avallabe in the for of cones.
| Nexen
oi ed the le modes
bi pn rend mode i ina
as is
Ss ) tbe medule bu these erie desis BE
sscpen binary fle. But as pr slabs we halon ome
= -_"mt 4
COMPUTER SCIENCE WI Figg |
CF) cp 5 rue tne
Sa, © frat mle et fetta | 5.4.2 Appending Record
ssh bin write ogg Is and append the new records
weno mle
written in the file. Just as you normally writen binary file, ute Mt 6 spn Oe Or
you write records while appending wing the same dept oma ede a or"
function ofthe pickle module.
ae
program's folder and iyo 7
3
no, name and marks) from user and waite ont a
he user and write ont the file as long as the user
jow you some garbled, =
Fm,
ete se nnee Anarene Heep lew
ST
9) Write a program to get student data (ol
“The program shouldbe abe wo get data from
‘adeclare expty dictionary
‘open file
5.6.3. Reading from a Binary
‘Once you have written onto a file using pickle module's ump) (as we di in the previous lst
‘The sample run of above you have written onto file using pi if module asit would
program is as shown here section), you need to read from the file using load() function of the pickle
then unpickle the data coming from the filewing syntax : Fer 5 fe HANUNG
BB ci se sere ating } a a
ynde>) F ram below, we have used
cas a In the prog ve used both the try. except block (in programs 5.11 and 5.12)
with statement (in programs 5.13 and § od
a file openin file-handle fout, z the wit 14) for working with the files. Ne ider the
ad an object in nemp from: YOU wou lowing program that is readin 18 With the files. Now cons
amma a fen ern fh eo a rom the file you created inthe previous program
) the read dota one nancy nem
511 doesthe same or you. It reads the objects writen by program,
fem open te fl Empat (created in rogram 8, ead the objects write init and
Following program
vera and diay them, Butbefore the program 5.11 read the following box qa
You can now we he eject wl way fe we pn
teterertte
lod om reaching EOF
Now that you have an idea of how to read and write in binary files let us write a few more
programs before we talk about searching in and updating the binary files.
‘open fle created and used in programs 5.9 and 5.10 and display
‘tohold read records
close filefaces
bE. ‘COMPUTER SCIENCE van,
: oper 5 FUE HANOUNG nail
following program is just dong the same ising
fan variable namely found that is
False initially and stores True as son asthe sur
tested for its value and accordingly the Py ‘is successful. In the end, this variable is
5.18 Wit «program o open fle
p Gyn teres and search fo recat with rol numbers s 12 0 14 f fou,
Toso
pene ney fea wit 0G in ie
smport pickle
string ="TiS:
eta
sry teary threats
sw first Line, This 4s second Line.”
Fle msfleinf open i 5 190") sc.” #open binary file in read node
‘# List contains key values tobe searched for
print(vFile successfully created")
ste ove programas created binary le namely yfile.nfo that stored the given st
binary format. :
5.14 wenes progam wd fom te le myflelnfo ese s Prone Pram
we rg encountered, Le, play all the fext before he leer
e))
‘The output above is : mi
produced by above program is as shown below : - LP 5.16 Read file st dat created in erie programs and day records having maks> 1
1 sins 4s my first Vine, This 45 sec ——— St x free leer eel *
Tas" seport pi yates
st ‘gaectare empty dictionary object totold read records
rocess with the with Block
record in stu dictionary from fin File handle
sprint the read record
aed 1 chi fil dat for marks > 82
ovary oecnog in fe Sa va
pares a) ‘eroVIno": 1, "Name™= sgiat, ‘marks’: 83.57
search successful:5.6.5 Updating in a Binary File 3
‘You know that updating an object means changing is value(s) and storing it again,
wooed ina file is similar and isa three-step process, which is:
{@ Locate the record to be updated by searching for it
(id Make changes in the loaded record in memory (the read record)
iy Write back onto the fle atthe exact location of old record
“You can easily perform the ist two steps by whatever you have learnt so far. But
Ye ey Tow he lation ofthe ecard in the file and then ensring tha
ene mriten i written atthe exact Iocation. Thus, we shal first talk about inthe
‘ab-ection how you ean obtain the location ofa record and how you can place the
fon a specific location (requirements of updating ina file)
5.6.54 Accessing and Manipulating Location of File Pointer ~ Random Access
Python provides two functions that help you manipulate the position of file-poiner
you can read and write from desired position inthe fil. The two file-pointer location
Of Python are tell() and seek). These functions work identically with the tex files
the binary files.
The tell) Function
“The tell) function retums the current postion of file pointer in the file Its use as per
following syntax :
OTE ;
7 ov es are tet es
Following program is doing the same. a
Pp 5.21 You created the fle compresultsv inthe previous program as shown below. ;
Wie a program to read the cv file a
sen oom oe he cord of his fe and display
Nate. Before we write the code or this program, recall
yoduce the result as
‘Compare the above output with the sample run of previous program (program 520). We never
tntered empty rows. Then where have these empty rows come from? Any idea?
stored as
spank’) \r
be sa tin was appeal with EOL charac “8
['shradha", *4500", *23°]\r on Window OS bau of EOL ratlion
\a
[-Nishehay', "4800", °31°] \r
\a
‘So what is the solution ? You are right again ©. We should have created the file with newline
argument set to null string ("') so that no EOL translation could take place.
this situation would not arise. Programs 5.23
es
AL What ae text files 7
2 What ae binary les ?
3. What ae CSV Bles ?
4A. Mame the functions used to rend and
ite in plain text fies,
5. Mame the functions used to read and
ite in binary Biles.
6 Name the functions used to read and
‘ite in CSV fie.
(i) Method2. To
with newline argument set to the EOL character of the
(OS where the esv file was created. For instance,
created the csv file on a Windos
reading with newline argument
the EOL on Windows is stored
Recall that the table 544 lists EOL characters on vanous
ICRSE Sample Paper 202021] operating systems.‘COMPUTER SCIENCE Wn
yp sn ane histatins melo 2 Tite ere Leto av ag
po scar ee ey
royam
newline = "\r\n") as fh:
\
Now the le il be ed coding :
(nd oftine an na sso ng”
‘Let us now treat the earlier listed problem of blank lines in between records using he
listed above. For this, we shall create the file with newline argument and then we hl
ny newline argument while reading as no EOL translation would have taken plac.
Programs 523(0) and () are illustrating the same,
‘The above program created a file as shown above,
Let us now read fom the bow
"e created file. This time we need not specify the |
‘argument as no EOL ion | doing
rant hasan place, Program 523) doing he
jane 5 FILE HANDING
pr. ‘write program tread and diply the contents of Employe sv created in the previous progres
| rtesy
gem PO
Te) 28 fh —— Sn er ne ome
van teen oad
with open("Employee.csv"
Sm ki in en he mod
nee how foe nl
With this we have come to the end ofthis chapter.
DATA FILES IN PYTHON
nt Pi Progress In Python 5.1
“This PiP session aims at giving you practical exposure to file handling in Python.
) flanction suze o open a dat flea program dough afleabjet oro file-hondle)
+ A filesmode governs the ope of operations (eread/ write / append) posible inthe opened file. refers
© While read) reads some byes fom te file ond retas i a orig, readline ) reads @ ie ot atime ard
odlines() reads ol the lines from the fle and eu iti the frm of st.COMPUTER SCIENCE WH
votes
erro a cy el oh 0)
7 eel de pian l een
om este fle pre ecedein
Cn ee emer feo nee
Soon a apne vow ooo cos
sce ama eye
« Roopemncnhigan tase
etnias
Foe oh aaj ects nde ta ae
Tenge crate
Con ene nme es EL eatin
sure object which converts the user dat ina
OTOs iy
MULTIPLE CHOICE QUESTIONS
Information stored ona storage device with a specific name i called 3
(@) array tionary {file (@ tuple
2. Which ofthe following format of files canbe created programmatically through Python tag
files (€) Video files —_(@) Binary files |
(file « open
(@ ile « opentfie =
seit", “Ww")
wt
pope FRE HANDING
4. which ofthe following option is the cont
Uharacters ofa text file “Notes” ?
Python statement to wead and display the first 10
(CRE Paper 223 Cem 1)
11. Which function i used to read al the charac
( ewadcharacers) (6) readal()
4) eadline() (0) readline)
13, Which function i used to write ll the charac
4a) write) (0 writecharacters) (9 writeal()
14 Which function i used to write alist of tings ina ile?
(0 writechar()
(@ weiteline( ) (6) writelines{)__(e)writestatement{ ) (4) writefulline)
15. Which ofthe following ts mode ofboth writing and reading in binary format in Ble?
bt (Owe (owe
6. of the following isnot a valid mode to open a file?
(oa 0) rw or wr
17. Which ofthe following mode in fle opening statement results or generates an error ifthe fle does
(@ When you open a fie for writ
(@) When you open a ile for writing if the le exists the existing fil is overwriten withthe new feM
22. Which ofthe following functions
o
‘COMPUTER SCIENCE WITH Prt,
a
the poston file pointer and retums It new px
Gai) @) ten (ofeset) toy
(pq,
(3
tain the binary format?
(@ send)
(ofa fle object?
{CBSE Peper 21 Gam
26. Which ofthe following statement is incorrect in the context of pickled binary files 7
{@) The cso module is used for reading and writing objects in binary files,
rc)
‘The load ) of the pickle module is used to read objects.
(@ The dump) of the pickle module is used to write objects
127. What isthe significance ofthe seek) method ?
(
socks the absolute path ofthe file.
(©) The pickle module is used for reading and writing objects in binary files
{CBSE Paper 202 em
{USE Pape 200 (en
(b) I tells the current byte postion of the file pointer within the file,
a)
®
«
File_object.seek(oFfset [, reference point])
seek(offset [, reference. pott
seek(offset, File object)
ter of ev files is
6 Te Lerma
Ip, We ean suppress EOL translation i text file by giving ‘argument in open( )-
th, The fle mode to open a binary file for reading as well writing is
{9, The file mode to open a binary file for writing as well reading is, .
2b To specify 2 different delimiter while writing into a sv file,
cov.writer()-
TRUE/FALSE QUESTIONS
1. When you open a file for reading, ifthe fle does not exist, an error occurs. 7
7. When you open a file for writing if the file does not exist, an error occurs. £
3, When you open a file for writing, if the ile exists, the existing file is overwritten withthe new file.
1 Assertion. Python is said to have broadly two types of files - binary and tet fle, even when there
Fe CSV and TSY files also.
Reason, The CSV and TSV are types of delimited text files only where the delimiters are comma
And tab respectively
separates the values in csv files is called the __.p- COMPUTER SCIENCE wan HANOUNG
6 rH Pr 5 rue
work with text files, CSV files and = tats
12 Awertion. The ile modes °F, “w", “a” work a ‘TSV files a rte a fantom tats tha cee flere nd prs te
ted text files only.
lo reveal the type of file these are being
Reason. The binary file modes fix with regular file modes. ‘wed wg,
4 Accenon ‘Piling she process whereby a Python object hierarchy is converted int
Reason A binary file works with byte-streams. rs,
5. Accenn ‘Pking isthe process whereby a Python abject hierarchy i converte into aby
(0S Paper 3205 Cer 1}
"MOTE : Answers for OTQs are given at the end of the Book. —
Solved Problems set started isto (© qui talking and begin doing
(
a
(0 The way to get started is to quit talking and begin doing
(@ gniod nigeb dna gniklattiug ot si detratsteg to yaw ehT
fhread 2 wil rea the entite le content and place the file pointer atthe
the fureadts),it will return nothing as there ae no bytes to be read from EOF thus