File Handing Class 12
File Handing Class 12
TeA°t File
It ofdu:- .-.~ -~...__, ."-; c·, - ~
.i ~:i;:n.~
g-mth.~ h ,m~ ulk---mutt:Mt m !.~ ~~l
, .:'!'Tea.1JU.~~ ,~ !b, -~ -u. .k.;.--::..- :-. :.
\X ~ ( ' ~o . iur. . .,~ ' r-........· I." !;\
p:2-.:-r.
n~c . .
:ut" u~.dh s.: ... , - t\l: "' - .. .
a::c.n.~,~ u,-.:J m : i - - ~... ~ J. ,
<: .o:t
qI
\\ I 'I'''' I I 111, , 11" I" ,III.-,, 11111, I "" I 11 ,, J1111 I ' I r 1Jii11l11
11111 llh 1I II II 11111 I I I II II II 1111, I,' it! ,I I I I
1 IP 1l1• 1 \11 •\\ 1111 1 !ill II iillil\j 11,,i 11\lii\\
~.v,.1gr.untnin~ Lrn,''l ,,,.. I I\l'l1,.' • h.11-i\ 111,, lhll\\(I Ht'IIIII\ ', lhll\11 1 (II 1111 1 111, 1
• ' ..
·::- .,~ luh.l.: ~.t.,.
.. ._\ ,,-.,. ,II\' I\\\\
1.'p~:n ,;111..l 1..k,~1..-. lid~111,.• \\111lrni:
j- t ,;1 l\ ,ih.ln ..lllf-ll,lf_t', \ t'U lh.'\'\l I\\ ()pt'I\ it lll :\
l'r,1~1':11\1 'l'o n1n-11 th1· ltl1· w,111g 11p1·11() 1111•11111d
f 111w11( .. , 111•. l xi", "w"' l
·:mnJc .1, r~r the l1k· nunipuL1u . .,n t.1~k ,,,\I \\,\!Ht\) p1i11\\"N c11111 1 11 1 111{ 1 lil1 1 : "'. f.11i1111L)
p1·111\("(l11::,1 1 tl il l 11111: ", 1 ., 111 11il)
p1·i11\ ("l)l\\1111111\ llltlll1 1 : ", I ,11111(11)
ning a File Output
·: h.lndling. the tt~t rc1..1ui1~t1h.'l\t i:- t,pcnin!:, .l t,k. N,11'\l' ,11 tlw 1111.· · Ilk l \t
~.if:., orc-neJ. re.1J. "rite..1ppcnd. 1,.h,st·. 1.'t( .. 1.\111 lw ~ 'lo~nl 01 l\lll: l•,1ls1.·
• ~t..i on ihe tile. t )pen in~ m,Hk: "
::,m ,l file. or~n~) ,m·tht)d l:i LlS~1..i in l\tht)ll.
( ,losin~ a Fill'
ect open l ti l P _name[. arces s_nwci~ J) It is 1mpmt.1n1 I() 1.IP,1.' 1,b a, snn11 ,ts you It 1vc l'i11i!.lnd
\'IHI! "01-k with l,lc. ( )p~ 11rd l1k 1s 1. ln~cd liy l ,tlli11g, die
mieu:rs
cl1lSl'() tnl'tlwd 1.\I n, lite uliil'l h,
fik_name The file ,ume .1rgument 1s ,1 srrin~ v.dul' dw
P} dwn .t\llOlll,ll icill) \ lnsr, .1 1,k wltl'I\ t It~ 1l'll'l l'm l' olijr, t
conuim the n.,m~ 1..)f the file to be t)pt•nt•d.
ol ,1 IHe 1s tl',1ssi~111.·d to .tlllll hl·t l1lr. It 1s .1 good pr;tl tic l' to
l'C'Cess mode rhr .h:~-t'~S l\H)dl' 1..ktl'Ltl1il1l'S rhl' mnde 111
llSl' 1h1.· dn~l'o llll'thod 10 , !mt ,I Ilk.
iiuch~he t1'e h.b fl.) h.· opent'd, 1.l'.. re.id, :\ ntt\ .1pp 1:nd,
~c. This is l)ptiorul p,1ramt:tcr .md th1..· def.wit Ide ,1ccess ~,nt.1, I I l11 0ll.lPt I .l lo <i1 1 ( i
mode i, read\r). I\ thun n1.1kl's surl' th.It any unwritt<:n or 11m,1ved d,11:i 1~
l'h'"''" ,_\", ,,,I\ I,, ,,,,~,d 111,I d,, Iii, nl,1,,1 will h,
"'"
I , , 1, ', (' 1J
\
1
1•:1.1lll\l\\1I ,,, 1111 11'1\lllllltlt\ ,,I du 111, ,
\ 'n 1h{ 1,1h, 1 h 111,I. 111 ''l'l'' 11d 1110d,, 111 w d.111 will lu '11-111,111
, ( ,•11111loy1·t: ; ">
.,
11( y,,
hl.1, ,I 11 1111' , 11d ,,j d11 p1, \'lull~ d 11,1 Pi !Ii, 1111 11l,p·1 I j,. ,11 J/1111 I /t,1111 1 11
th, , 11,I ,,1 1h, 1,1. • .,. "' ('IIIJll1t/l'I . Y-111,.,111
, ',I I I I'' Jlil" I ,
'" l'ul,,111, th,,, ,111 '"o 1111 tl111d,., 111 Id, 11h1,,, P( wlii, Ii 1111· ,.. uf 1, 1111 ,Joy,•£ ; A•J11,111
l ',jjl/'I JJ:011,
'"' ,I It• \\ 1111 d n,1 11111, ,t Ill,, h111f•J 11,11111 ,,/ ,·1n11l1,yt•t•; Y'.y,1at1
--r- · -.2. ~~
~ ~~
,_ ',,.~
- --nt 1i ~
~ =-~ <".:"'"-!'.~.l.L:.~ ..._..
--:::.::=-~ ~ -- ..:.-.~~ - - ~ ~
~ :_:: ::._.- ~ ; ~ ~s
~
~ - -~c;_:g_ ~= - - ..,, ~,c-..::::.-:-.:... - ,....,.-$ .I. - - :.:::r:: ~ ;;;;;::.
-~- -~~~ -~~~
-- -
0---";;- ....I.
~=:x:~ ,= ~ ~-
P: ·;:: z:::;j -=:-- - -~ - ~-= -- .::___ -~~ --=. - - ---=c
(CJ ~,ead;;n-e()
TI::-~
___.., - __ _, c'. ~ . . ~ .. ~ - -;:;-:e:
11c1mc inpuu " rnte, · llcllllt' \\ 1 il~lllll 1,1 )0111 rnH' ,1t 11 ~11li1111111, lo, di 1·11111 rn1,ly,
1. appcncl(lldffif'! ' \11 ' ) lll ll',l1'1t' I: " ) fll.llllll' 11111 ,l"l'.''1111111 1H·11h 1111 v,1111111, 1n11qu1111v, &
,.w r·i t elines(l) lllf"llllllH'lll 1'\ ,1111i11,11i11m ,111d "lt1111I \l'~1111111 .
'(l'i('{)
I ,l I (b) rcad(Isizcl)
1'1,i, nwchod ,,H·rtl1r, how 111,111y I l1,11.H l1·1, d11 "'"'l\
1'~ir11 ' records do you wrnt . 5 should rl'tllrn .
H'''' 111.1111,
1
. .
unl' of te.1dm : Sic.lhaarath . . Sh Synta, d i I 1' li a11d I c 1
, . 1·1• o1d ( 11 J
~Jlf(f 0 • . . ' " arma
1111
1e of tl'Jcher : N 1sha M"ish . Herc. <. Pikl Lrndk .. is dw Ilk ohJn I l111ldi11~, oi,1·11 lilt-\
fJJle r 1 · • 1a
1111 e ot re,1chcr : Soniya Yerm rcforencc .ind ' n' determines 1111mhrr of d,.11.11 fl• ~
n
f;ifC r ' . a 1
£.~ irr f1Jl1H~ ot_ racher : Ki ran Gupra I( no argunicnt is 1-ptx il1l·d, it 1T,1tl., ,1 1011q1ll'l1 li,w ,111 I
fll rtr 11 •1me of teacher : Ansh Sharma rernrns sering.
Program To read n bytes from text file .
(itJled file
my f i 1 c ope11 ( ' M i 11 cl 11 l. . I x L ' , ' r ' l
Teacher.txt• s my r i I e . r cad ( l !i )
pri11L (s )
Siaraaratra Sha~ma my r i 1e . c l o s c ( )
~1isha 'lisrra
Soniya Verma Output
Kiran Gupta
Welcome co arih
Ansr Sharma
Program To read n bytes and then reading some more
bytes from the last position in Lext file.
myfi l e= op en( 'ari l1anL. t xt ·. 'r ·)
s=myfile.read(lO)
Reading from Files print(s)
Afrer writing information into a file, you must need co read s l =myfile.read( 30)
~lucdara at some point. Python provides mainly four cypes print( s l)
i read methods co read data from file. my f i 1 e . c l os e ( )
Htrr, dJe content offile 'arihant.txt' is as follows Output
Wdcome to Arihant! Welcome co
u·dcome co your one-step solutions for all your srudy, arihanr!
prmice and assessment needs for various competitive & Welcome to your one
·ecruirmenr examinations and school segment.
( c) re adline ()
These methods are as follows
The ~eadlineq method will read from a file line by lint:. for
(a) read() r~adlme(), ~ lme is terminated by '\n' or End of Linc (EOL)
~is method returns a string containing all characters in a (1.e. .new lme
. character) · When •·n<l
'" c 11c
01 I l
c-.1 .1s. rc:ac1ec,
k. readlme() will return an empty sering.
Syntax Syntax <Fi 1e Hand 1e >. read 1i n e ( )
'fileHandle>.read() · b y line.
Program
f- , . a file's first three 1·mes 1me
To read
Here, <FilcHandle> is the file object holding open file's -open( ar1hant.txt','r')
rd'crence · We are using .
. a 11c.1 e namej y " an'h anr.txt " storing str=f.readline()
IQrne comenr. print(str)
str=f.readline()
Program To read entire data from text file. pri11L(str)
~Yfile=-open( 'arihant. txt'. 'r')
Sl~:af.readline()
,=myfile.rec1d()
print(str)
Print(s)
f.close()
my f i 1e . c 1ose ( )
<.;OMPUTUt S~II ~,
1
A.1li11one I ·•,t+ 1
94
Oluplll f' ,einr,ving all l·,O( cl
fjk ;1 1cr · 1.1r;1t
Outrut \,r, o f l(•r,,i
\\.dcom~ l•) Jnh.mt! II . ,111dy. ,Jil(.('',; 172
Wdrom(' w q,ur one i.iq,
I
Ml u11on~
(c,,. .',mpcd1ivc
1 )our
&
I
T(lt,11
.
'jl/.l' II
r I lie file: I 75
pr:teti~ aml .l.\'~"ITil 111 nCl•1.h for ,·.rnot~s o
. To print the size of entire fil e in byt
l'h I Ill
To, end a entire file line, by line.
. , l'nW" 1,llll ,·st11<Jrn,.
I f / L' ' r. J
· · t,
f I pr. • .. r1hi1nt.txt , r ) f,-=orr•n
w ,1l Trltt:: str"'f,read()
vr,lt..readl•nr<> r =1en ( s t r )
f=open('student . txt , r )
(d) readlioes() s=f.readl ines()
This method wilJ rerurn a list of strings, each separated lcount=lenrs)
by '\n'. .
This method reads all rows and retains the newlines
print("Nurnber of line s in fil e is: ",l (
print(":> ze of f ile after removing all EOI. We are using a file namely 'srudenr.rxc' sroring rhe CO
Sol, Rahul Vcrma, First division
charar t~rs t blank ~pac~s : ",s) 502
prirlU"Total $1,e of tt.E> 1ile: ".Ls) • Reeccsh Deshrnukh, First division
f . clUSli:'() 3
So , Aaditya Mishra, Second division
4
S0 , Aradhaya Sinha, Third division
SOS, Manish Sharma.Third division
,ir1dlill~
fih' lf ,
to opl'n thr file in :1ppcnd mode, 1,y ~crti11g .!· as rhc mode.
r,·studrnt. t.,t. Wnh file accc\s mode J', open () function fir5t t.hccks if
1
,f O!!. pat h. i Sf l l C ( f ): file cxi\ls or nor. If the file docs not cxi~t. 1hen it crates
~
.1·e11c1mt"( ' sLt1drnt.txt· , •st.uuentl txt,) ,rn empty fi le Jnd opens it. WhcreJ~ if file exists rhcn opens
05
fl•':-tudcntl.txt' · ir. Yo u can also use file access mode 'at' co open file in
C1h•Ope11( fl, ' 1·')
reading as wel l as wri ti ng mode.
print("Content of new fi l e... " ) ~yntax
FileObject = open('t1lename·. ·a· or ·a+-·,
for i in ob: The content of 'computer. ext' fil e
print(i .rs t r ip ())
Computer science
ob . close() Head
e' se: Authors
pr in t ( "Sour ce file doe s no t ex i s t") Proofreaders
Program To append data into text fi]e.
l)utpUC
eoorent of new file ... f = open( "computer.txt","a")
f.writ e( "\n Welcome to our company " )
, 1,}lahul Verma, First division f .writ e ( "\n I hope you will learn more here")
0
~2.Reecesh Deshmukh,Firsc division pr i nt ("A pp end the data
0
I
rrcc l 1' , 1
1
II II I ,., I
95
File does not exist Typically. this means chat thl' ,.Llta wi\l be copied fth
i ;·~· r:1~ -~~~~ -~hi~h ·;;;~. ~~;;; ·;~ -h~-<l~i~~~d:.... l
Jrooram
t, buffer ro the op~r,ttinrrt' system butTec(ft', • ,~.,1;t .:, ,,1
Python autom,aically flushes the fi\es when 1'
ivh,LU' Hut you may wane to flush the data before ck
fiJc iUcct.ufully deleted Syntax l"ileQbjecL.fluslH)
/j ,. I , <nvwu , , ,, ,., i
I Jll}/Jf(Jllv 1
r j,
I~ I M• 'l,o,I
I I 1 1 1, t I ti ii 11 I
1, I I I 111 If'"'" I
IJ{''
' I I I,, ,, I I I)' Ii,, ,,,.,' I ,,, ' ',.,,,~.~· ,,,~. j,
-~.
I' iI'I/
I I I I q Ii I I II ~ ,1,1,,I if,,, 11'11 , , IIIIH lfHj ,I
I,,,' II JI I ..
I t I It II I ,,,
tl~ltlff I I'
1 yf,
1
lf,14
I
,.,,,
I' 11 I11, JI' I
111•11 r
', ; ,, ,,
" ' ' lj I t" I' I /,
Hf 1/1 '
'/ 11/ ',.. I
lfjlli/11 1 Ji! JH 1
I
lii ,H• ~ lht ,} Ht t,,,_, . J
111 ,,vul,
'I I J" i\ , tHllfl"' I,,,,,' I OJ/. i.';1·
I 111 tli1 1111 111111111111 ,, 111t ~ 111 111 l110, n·, iii I,, Id,,, 1,111p11, '/I"' I I. I •
{} ,, 1111 •,11,1,
I
1Jf 1
1
tlJ' P' :t,10111, :1
,
f:,: .,
'
,,f 1·;'
111,llt I iltt, II 1111 111, Ill d Id, 1111 ili1il ~I I II/ I '
ojJ
/I j, I' j/11 p11' JIJIJ/I ,1 / l:i' '.l}l:.0 m,•• th.~ W ••e-
Ht,tHh,111 /\;•1 1•w~ 1
Mt·tlr<,du fi/, ,I'; II j, 11 1111 • 1111', /J/ 1 111 ,m,j 2 lljf_" 1 ~ ~ ►
✓1wd,I I,, 1,1k1 n :,t, tlw 11'1 1
tt'iU ;~,· dut,
\\ 1 11 11
) 1111,. "' 1111111 ltl, Ill Wil l,'" I 111, , d,,11 l,y d1/1111l1
do 1
1 1 1 111, ~111111111i ,d I l1lii 1111 •1111, 1 !111 11,,dO n11d1 111l Pr11v;n1111 /Jwf'Y H11 JJ' ;•,1t1,-'11 v11de p<,1fJe• _;; ..,
dw111 ,, ,ii~ ,11111 d,, l,11:l11 1li11K 1,l ,1 lllL ,11,d w111, 'J
IH,111 1;,,, 1111 d pwil H" d;ita (Jf' urfl•m f.1f/,1t1,,:J 1.1··
111 d,,.,/ d w, 1\'ll w, 111 ij d 11i1 ,11 Ji,, 1 wf 11I ,L1h1
1
11 1,d 11,, ;;t,1/J IJ'J',111,11' t:1t,• fr,m, i},•·M,.:.
1
I ii, 1 1 1111,, .111, 1111 1 ,lo , 1111, 111 ,,,,~111,,11 11, tl11 Ill, win t( '
1 1
111111'/f I '!',
\4, J11111,, Ill II 11lilill "I ll I ,I, '''"' I 1111 (, ', 'J!IIJlld.l·(. '.11,
111 ,1,,111 ,,,,, 1,I, ~ I "" [Ill d11,d11 111 p, 11111111 1,111d1,111 JII f l'II~ l I ,, , , IJtl f fl. l ·, f 1 , I I l < I •
1 11
11 I 11l 1 11, ~ lit I Ill, '111 ~I ,,,, tl111d1, 111 Ip }''I I/ Ill lllilll/,.,11l1H1 '
I 'if!' 11 1 l 1 I,,. I [
ti,, ,,,,~111,,11 q/ Ill, ,,,,,,,,, I 11 11d ll111 1t ,,,,,, J ,Ill ,,,,,(1 ;fl/I W)/1(
l
I . r ",,rJ I 1 fl' I ,
I 'j
111 1111 1 11•11,d 1111 ,l1J11 11 Ill du l/11
1,r i 11t I "l! i • I. i r • { .
lt 1H( > Mt tliod 11 11', I . I I I I ' J
I I,, 111, fl,,,,11 1 II,, y1111 ii,, , 1111, 111 p,,~1 11,,1, wldtl11 till /1)t , Jir l rd I "(.!Jr r ~ nt J,<J' 1• 'Jfl
1111 1,1111 ii l11 l1 y11 , l11,111 dtl l•t/\/11lt/llf'i o/ r/11 id, I • ,,,.,.~ I fl'I I
-~'"II I I I, I,, I ! I I I , I J 111 I , ', j 'J 1•,1 11 It I ( J
w l111t , Id, 1 ,1,1,,, 11; ,1,, , J, 11ull1 ,ti''/'' 11 /1/, 1nlr,!i"f,,Hr£11t r,r, i' rr ,.;t
I ,' 1 1 Y l 1'J,
/V, 111•, ,,,, i11, 111l11c· ,I ///4 lh/111! /p 111/11;1111, / I• t' ,1111 /,/f. J/!r, 111//1•11/
1
rd
sys.nderr It stands for standard error. This file object is
forerror mess,ge only' even ,hough irs ourpUC goes
new tile 1or appending and writing
To save any types of data (object structure), Python This method is used ro load data from a binary file.
provide~ a module called pickle. The pickle module is ~sed Syntax
for serializing and de-serializing any Python obJect import pickle
structure.
Serialization is the process of transforming data or an object
in memory (RAM) to a stream of byres called byte stream.
Serialization process is also called pickling. object=pickle. load(FileO bject)
De-serialization or unpickling is the inverse of pickling Ir is important to know that pickle.load0 method
process where a byte stream is converted back to Python raise EO FError when you reach end of file while r
object. from file.
ln Python, pickle module provides two main merhods e.g. import pickle
dump() and load() for writing and reading in binary files. file= open('imp.dat', 'rb' )
U'!ting ,i 11 n1pf ) vtc· hod listl = pickle. load(file )
file .close()
This method is used to write objects to a file. Before use the
dump() method, you first have ro import the pickle module. print('Showing the pickled data:')
Sy11 t,1 ... cnt = 1
impor t pic kle for item in listl:
print('The data', cnt, · is , i te·
cnt +~ 1
pic kle .dump (ooject_to_pickle, FileObject) Output
Parameters Showing the pickled data:
• pickle is the moduJe which can be used co store any kind The data 1 is: 12
of object in file.
The data 2 is: 65
. object_to_pid<le is eirher a variable, an instance of class
or Hst, tuple, ere. The data 3 is: 45
• fileOhject is the name of file in which you wam ro The data 4 is: 86
wdte. The dara 5 is: 57
<)<)
, u:1~ic File Opl'r,1thll1S on Tt'\l No 111, 1111' ,m 11 1111.~ "/1I<' 1ut111!' I.Y ,rr>I'ur,I', IXt ' J111 ,uw,., 1/,e , 0111, ,11.
•';;';iin;1n Files iu P, ll'.011 < '. oll1:µt
U ,t\\
tl 1.11 ,n11, likl ,1.:.11dun~, 111,t·1tiiw I I ·
jkPjll • I' ' r,•lll\lflg ,111d I .l'.l llllU
·" I 1,., 1 (ill· ,Ill( ,,in ,11, l1k ,Ill , ,1111 • S .
I 1.:. , o, we will
, 1111
tlJll'l,lflllll\ Oil ) Oil ll'\I Ilk
Studum
' I,,,,"''",hr,C . Staff
" t1ltt~ ,1 f ik 1'1rn 1 1111 To insert element or data into an
~1·•1r( ,rl' through data in a file · •
~l.11 , h111g existing text file.
1 ,111 • I I h , ll 1s a very
,1,, II 1lll'III lO IC,ll t Houg a file ig110 · def in5erL( J:
"
1
,,,, 11· . . ' ring most of
. ,o ind 011 ly proo:ss1ng l111c~ which meet pa, rt1cu •. l import pick le
ti 111, • ar ' d. )
filel = open( ' col l ege . txt' ,
,-,rfl,I• 'I
, , · u1ill'I, rt Jue 11amely 'school.txt 'storing th e content. whi le True :
11 ,r,t c • ,
y = inp ut( " Enter some th ing : " l
..~o0I p; ckl e . dum p ( y . f i 1e 1 l
(Jc hco ans=i nput("W ant t o ent er more data Y/ M" )
_.,1,lcJJI~ i f a ns . upp e r ( ) == · N• :
brea k
,oor1' fil el. clo se()
~r~r,"11To search any string in text file. in ser t( J
de f che ck (): Output
datafil e= op e n ( 's chool .txt') Enter something: 'Subject'
1ound input ( "Enter any s tring to be Wane to enter more data Y / N Y
se or cll ed: ") Enter something: 'Study'
f == false Wane to enter more data Y / N N
for lin e in datafile:
if round in line: Delete Data from File
f = True Deleting the data from an already existing file, can be
break happen in two ways are as follows:
return f Type 1 For small file, which can fit into memory, i.e. a few
<•.::he ck( ) Mb's.
•f( f •= f rue):
Now, we are using afile namely 'company.txt' storing the content.
print("True")
Company
~1 se:
Department
print("False")
Output Manager
tnrer any .ming to be searched:
Employee
'xhool' Project
rue Program To delete the second word from a text file.
Enitr any ming to be searched: def delete():
faculty' 1-1ith open('company.txt·. 'r') as f:
~~ l = f.readlines()
f.close()
lnsening Data into File print ( l)
li;rning data in already existing file can be happen in rwo del l [1]
'•}l: print("After deletion", l)
f=open('company.txt'. ·w')
h1<:rtion at the end of file or insertion in the middle of th e
f.writelines(l)
~· But there is no way co insert data in the middle of file in f.close()
Ython.
delete()
I() ()
I All/11one I coMPUTEn sc..:11.
~(:,
. ~I;
(. )ucp u c
At., ,c<·d Fil e
( •.
[ l...-.imp.mv\n', ' l )ql.lt1111l111\11', algo1 txt-
'.\ l.111.ii_:l·r\11 •• • I ,n ,1 11 ,, ·\,, • , fl
1 . 'J
' • •' , I 0/l'\ I Get th~ ddtd Vdl~e to b e ae
\ftr-1 dt•lni,,n · I .
2 _ Open trie f ile for r~adirig f 1!!ted
f'l 'omn.in\·\n' '\ f · t '/
• \ • ·1·• r 11 p Ioycl•\n •, · P ro1n Read the completP fi le 4 ~ ro,,
• '1 o 1t
1;
r • 111,tgc r 11 • 3·
4 . Delete the data fron the 0 l!s,
''1>t•~
•
·1 ," liid1 wi ll not ftt in co m em ory o f·
r•or u,11· 1~ ht·, s. close the file •St ,
ll;-rr, trr ,,rr u,i11g ,1 file nr1mdy python.txt ' stormg the
ro111r11r
1 Updating a File
• (. ''- c rhc J,H,l v,tluc t o h e d ckt cd .
Updating a fil e in Pyrhon can be h appen in n-ia
.?. (. >p'- 11 d1L· file fo r rL·a Jing fro m it.
3 - Rc.'.id rhe co mpk·tc fil e into a lil>t. we will discuss about the replace a ParticuJa;Y l\ia,
another word. \vorq
•1. DdnL' the d a ta fro m the for.
Lrere we are using a file namely 'server. lou-'
a
.
sto ~~~
~- llo, c rh e fi le . 17,,
I. Ger rhe data value to be inserted With. eco
6. Open !sam e fil e for wriring inro ir. tts Po ..
7 2. Open the original fil e in reading rnode. s,,,
· W' rit <.' th e modified list into Ale.
8 C lo,c the fil e. 3. Open another (temporary) fil e for wricin . .
4. Srarr .
rea d mg . . I
ongrna fil e g tn,1·
Pro•rr•u11 T, d J
n • o e ete the line(s) having word(passed as simultaneously writing it in the ternpo sequen
argument). . . rary fue
impc, · t os 5. This is to be repeated nll you reach the . :
. .
rnsernon o f new d ata va 1ue. pos1~
def filede1(word) :
filel = open( " pyt ho n.l xt .. ,"r" ) 6. Write the new value in temporary fi le.
nfile = ope n ( " a l go l.t x t", "w" ) 7. Repeat step 4 for remaining d a ta of original file
wll'ile True : 8. Delete original file.
line= f i le l.r e adlin e()
9. Change the name of temporary fil e to original :
if not li ne :
b r ea k Prog ram To replace a word with another word.
import o s
else :
import sy s
if wor d i n lin e : import fil e input
p ass f =O
else : print("T e xt to searc h for : ")
prinU li ne) textTo Sear c h = inpu t( " > " )
nfi l e .w r iL e( line) prinL("Te x t to r e pl ace i t with:")
ti le1 . close( J
textToRepla c e = input(" >")
nfi1e.c1ose()
t 1 I l'd e 1 C • ~J, i t e · )
temp Fi le ""' op e n( " se rv er . l og" , 'r+'J
for· line in fil c inpu t.i n put("server. log"
utput
if textTo Sear c h in l ine:
I. Cer rhe dara value to be deleted. temp~ i I e . writ e (l i n e . rep 1ace(te xtrol·
2 . Open the file for reading from it. r c h, Lex ttoR e pl ace)
.3. Read die complclc fik: i11ro a fol. pr•int("Match i s f o und and
4. Dclcrc Lhc dara from rhc Ji~t. modification don e s u ccessful l Y")
f=l
5. Clo~c the fik.
break
6. Op(:n s:imc- file for writing into i1. it c r--o):
8. Close the file. printc"Match is not foun d " )
tempFile.close(J
\()\
sample txt.
The n-xt fow la1•ons will involve downloddlng
doing into
into doing
oi)
[check P~int ~
\'rl', i,•e are using a file nmnely 'smnple.txt' storing the
1, What is tlu· another 1w111e o/p1ckling!
.,1rnr. 2. pickle! module deals with which type olfiles'
1
~e
111 next few lessonsdwill involve. . downlo"'..l1·1ng a weo,. page 3. Why is need to close 1/"1 /ile a/ier pickling!
c.,ni
11, rhe lncernec
• c an
. reorgan1s111g the contci1 l s, ·111to use 1u1 4. flow many ways are !here/or deletion dawfi'om/i/e'I
chunks of 1111ormat1on. 5. When does pickle load{) method would rct1se EOFError!
\'nu will be going m~sr of your work using Python code
.. ritten and ex~cutcd tn Komodo Edit. WORKING WITH CSV FILES
going into csv files arc used to store a large number of variables or daca.
They arc incredibly simplified spreadsheets. Each line in a
in10 going
csv file is a data record.
Program To replace a more than one same word with
another word. hnpmt CSV Module
'rom tempfile import mk ste mp csv module is a built-in function chat allows Python to parse
from shutil import move these types of files. The csv module implements classes to
from os import remove. c lo se read and write tabular data in csv format. The cs-v module's
def replaceUile_path, pdLtern, subst): reader and writer objects read and write the st:quences
fcQ respectively.
#Create temp file To pull information from csv files, we use loop and split
fh, abs_path = rnksternp() methods to get data from individual columns.
wiU1 open(abs_paLh, 'w') us new_ ! i l e: The csv module explicitly exists to handle chis cask, making
with open(file_.path) as old_fi l e: it much easier to deal with csv formatted files. csv module
for line in old_file: includes all the necessary built-in functions. They arc
new_ f i l e . wr i t e ( l i ne . rep 1 ace csv.n.:ader csv.writer
(pdLLcrn, sub slll c,sv. rcgisttr_dialcc..t csv. unregister_d ialccc
I
Crc.m:d Fil<·
tl',p1.1'
I r
,o <,"'Jrc 1 ror:
fl-~ ~· sample.txt
• r.-l'f' .
,, replace it . h:
()f tO
wit The """t few lessons "111 involv" do-,mload1n&
doing into
into doing
( Check Point 03 J
, u,it art using a file -., 'samp Le.txt' storing the
namelv
1. What is the another name ofpickling'!
t. 2. pickle module deals with which type offifes?
e1c few lessons will involve downlo ad.mg a we b page 3. Why is need to close the.file after pickli11g?
11
che Inrerner
. c an. d reorganising the contents .into use1u
c l 4. How many ways are therefor deletion data from file'!
5. When does pickle.load() method would raise EOFError?
ks of 1nrormauon.
:i will be going m~st of your work using Python code
I I
( fl I II i I 1
1111 , ' • I·
J 1'1111 t 1111 I '!lilt) ' II I ll11
I' I ll \ 'Jh l, 111 11 I ,11 1•111 '
\ II ' lt1 t: l111l
Ii I I I 11111 11 11 •1•1 ltl I"
1111 I ril
II
• •l•• . 111
I
rsv I ill~ J--\(:4.. l''·' i\tod«· 'Ki),1,1 11 \l1.1m1a ',, HHJ()(J' '!) ,
J he-I°\·
lnll, '",
,lh ,fin, 1, 11( t,1,· ·" l l , , 1111i,lc, !Cl op('II thl' lw nii- ,I\
()111p111 • ,
1
f 'f\t.,11.,w .
, ' Kirit !',111li,1, /J
. . '"OrJ<J' •
, I >t11i;·,
~,, i 1
f'J\111lr1, '"l •
' , .' ',S ha:ya 1 1.1m1,1 , 31()()() ,
Chnr.lct~r /'Progr,11nmc1 • ' '~200( ' , I\,
Medo
Description ['DB/\', 'Ashmit C11pl,l ' ) B,111glr11 e1 't, I
Rl d fl ,~ dC'fdul' •node ar,J opens a file ror
. a csv File Using csv w .
.
\\
reJding only wnte rn 10 . · r1lt
W-1110 . f
Opers a fife for wnt,ng only Townrcan existing file, you ) fi tr\t o1, t11 htr1~,
rnus1
Overwrites the hie 11 !he file exists Ir . . modes (w, a or r+ 1rs1. hn 1 tr~
Ille does not exist 1I creates a new ~f w~iun~ sed in Python for csv files. tI111, ,
hie for writing funcnon 1s u . . 11
1
Append
Opens a file ror appending The file Tl11s. ru
c. ncrion writes 1tems 111 a scqucnq, (I·
. h b h 11
pointer 1s at the end of the file 11 11 . ) separating r em y comma c aracter · 1 ,
smng
exists. If file does not exist, 11 creates
a new file e.g. import csv , , ,
,~ Read 1- Write
with open ( ·emp. csv . w ) as f:
Opens a file for both reading and
writer= csv.writer(f)
writing The file pointer placed at the
beginning of the file . writer.write row ( [ ·Anal yst' , · Ad t,
X 1
Create Creates a new file Mehr a·. · 300 00 ., Y:~
Close a CSV File writer.writ erow(['Tester·, 'Rahu ] •,
Sharma', · 28000, ,
\\ hc.:n you are finished with work in files, it must to close .
writer.wr1terow ( [ , p roJe .
ct Manager• De
·
che file as soon as possible. To close a file, close() method
i!I used. 'Mahi Sexena'. ' 360oo· ' N
print("Data successfully add") , o•
~)nt.1x FileName.close()
f.close()
Read from CSV File Using csv.reader() Output
To read data from csv files, you muse use rhe reader() Data successfully add
funcrion ro generate a reader object. This function returns a Created File
reader object which is an iterator oflines in the csv file. We
emp.csv
can use a for loop ro display lines in the file. The file should
be opened in 'r' mode.
Analyst,Aditya Mehra,30000,Pune
S_rn tax c r:.. v . read e r ( <Fi 1e Hand 1e>)
Tester,Rahul Sharma,28000,Delhi
Here, we are using a file namely 'designation.csv' storing the
content.
Project Manager, Mahi Sexena, 36000, tloida
Manager, Kiyaan Sharma, 38000, Delhi
AnaJysr, Kirri Sinha, 35000, Delhi
Programmer, Shreya Sharma, 35000, Pune
DBA, Ashmir Gupra, 32000, Banglore
e.g. ;mport cs v @heck Point 04J
wHh open( ' designation .csv') as f:
t. What is thefullform o[CSV?
render csv.reader(f) 2
· How lo open a CSV fiie?
for i in reader:
prfnt(i) 3. Write about X mode ofCSVfile.
4
f.clo<;e() · Which function is used for writing in csv file ?
5
· How to pull information from CSVfiles?