0% found this document useful (0 votes)
5 views16 pages

Module 6 File Handling

The document discusses file handling in Python, including how to open, read, write, and close files. It explains different file modes, such as read, write, and append, and provides examples of methods for reading and manipulating file data. Additionally, it covers exception handling related to file operations.

Uploaded by

siyon25mech
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)
5 views16 pages

Module 6 File Handling

The document discusses file handling in Python, including how to open, read, write, and close files. It explains different file modes, such as read, write, and append, and provides examples of methods for reading and manipulating file data. Additionally, it covers exception handling related to file operations.

Uploaded by

siyon25mech
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

Page No.

Madule o&' Ale handu4


Date

Aile a Omputes aaocato


Sme selated data 2t holcls a
Bgecthc name ds ibelf The fles ax wed
to stre data permanenty m a nan
volatile memcoySuch asHad-aitk RAM L
Volatile memey ype because the data it
lost when oe turn off tht com putea. Henc
eedastoy sets T

in formatio es data for htue keteene

andlit d'hded fato tvO (atepnes


GeneLatly
text fes and birasy tiles. Text fles a
text fo human k eada ble forna
dimple
whereas bìngny iles have binany dats shich
under stopd by the computee o

maintain therr data b sinpla read ard


hoqrons
Loottine the text
a n e d t o read om es
shenasthec
fir.
se Aare to open it tocE
aile to fi enegntwe hane fo
Once Aeaaling e. wsitre reeoel
esdee to elese the
The Pxdes arica 0peatinda in pthon ias.
fllous
Openig a file
Operaton9 Renc os it )
feforh
k

Y detault
The lenane
Erample Qccesmodeant which that
d=
heshich fleobject functim Openinjhle a
") Dpen
Pythm
to att
open DeDant
bpen Malue iles
C Fle
a(tesSpecifiesthe Oant malnly has
tstrt the =
cottaining ngme
Dpen(ilename,
- t om a
modeo tile o built
access
Value lontains
needed
name
" helircctony
aCCe
r)
isrCreading) ic. Mode the io
B
read -
nane a ánc by Dpen
fo acceH=Mole he ()
ohichwe Q mod
Dpen)
nk, Moce the oo
e funetin
apenel file jo
arquneunto
et
ab+ at wb+ Wb rbt Description
rb Modes
ab

it It heof It It It It
newopens It [Link]
directory,
It otherwise, It It otherwise,
ile;it creates It file. opens opens opens
ue ItCXIStopens It notopens
opens opens opens opens opens
exist
ie in
athe the filethein the the file a file a
it
does a the a in a it a the
le file new fileinfile
file
directory, file the ficreates file filecreates file in in
not for for for in
for directory, in file. in reading reading
exist appending appending. createsbooth booth inwriting reading both both TABLE
ending appending a writing a
it new new
in reading onlymode.
the creates reading a reading 7.1
it file new file. only
creates
and only mode
ry, and in for The
writing and and The
a binary file. and and mode. If List
reading reading. new writing. file mode writing infile
a writing writing of
new
format. pointer
placed is binarypointer the
it file in file a
ates in for The file mode in mode. different
binarywriting. mode mode. binary format.
file for The exists, it is
a The placed
new pointerwriting. file in Ifformat. binary modes
tormat. binary The
pointer a file
file at file overwritesthe
the If [Link] file theat
of
for 1he placed is format. exists, pointer
is end a starting opening
iting. hie
placed file
of it is
pointer at the If
overwrites exists, placed is
the a existing
at file. file file placed of the
end the the file
is exists, it pointer is at
placed If overwrites
of end the the otherwise, file; it
the atfile.
the of file itexisting starting the It
at file. the overwrites placed starting is
the does the
If file. the of default
end the not file; the at the
If existing of
of file the exist the
otherwise, file. themode.
the doesnot ile existing creates a
starting file.
file. in file:
does the
If
Closihg
ohen the operations thaf are yo be perto mel
an opehed filedre iniahedwehave fo
Lcloe le ndlei to eease the esouoes

AHtaugl Pyt hon Comes wih a qarbaye


Collccor hesponible fr cleanit bp the
unreteened object from th memny
not rely onit to cloe a Ae Propes
hie the resouces
the file
The (losiry dene coitn a built -
Vloe C)
Syntax!
tileabjet. clot)

Exomple
= bpen (" fest txt", o)
fclon C)
Most Yecommeded eay of usins fiu
almg oitn Becau Once
thé wito' bloLk exists, fie automaticaly
clocd and fileDéje ct i deshoyed
wirn Dpen ( tegt- tot") as to
paint

The tle 0bject Attoibutes.


Once a iuis opened and a fu bjeet
cseated sasis peles t afermaten a bout
that file Canbe gadtfeed by aig some
prealefind atkibuts.
Thec are batcally four tp 4 attloute -

will ctusn True if the fie closec.


iu. cl o x c t Fale
it wll otheruwje yetuxn

de oito
fiumale Dt wil retuxp the aclen no
which
Actuennthe name the tle
tienameit wl

eapliitty t
aequied
cl retarn Tue
otherwe
Exanple
=0pch(" Newitt!, "")

paiat name tNestxt

Falle

PAntmocle

f-sottspa ce

claec)
tcloud ’tTue
oritin to
Opening Ae hare to pertorm
SoMe He

Syntax

method enables
angctiny to
Exampla
t=openCtettxt )
to the file tne 11)
to the tile

Readi foo a

to reasrom flee mut


bpen the tile fn theread iny mode (r mocle).
TheeQta Dumbee o4me thods Qrailable
fosYeadng we can au read (siu) metrod
to read the data
She prorided it wil erdupreadty
the end

cdene th
Reading
methad
am
readl)
any
he ead() method
methodenbes
the

homao2Pened tile

Sunax
ikobjeet read ([sie)
Ex ample

fseadl)
frond 6)

readline ) a metnod
line by ne ohenever Lori te i i t .
ilenejelt radlin
rom that
()it prns hne
leand continucs in tnú
the end of the tile:
Example

f= open (test tt', y)


freadlhec ) ’readh hlyne
eadibt anoine
fteadlinec ) ’tead t'i
[Link]) ’ T returns -the nextlint trom
the file
fitevseadtine Tt reacts Lntil the end of
the iu ang readlines. Tt
Yeturns the(ist G Iines read

file otell ) T return. the files


cursent posifhn
netnod tel c
tell ce about the uren
tclll) CLrent poitms
sthe potntes The
Bron a
tells
psesent:
whee
readlny
dile seek Cotset) Tt changes the

also change the pouiti


Seek C) metnod:
petntes wtn he hele Paseeltobe moveo.
number bytes
A
ArAume to tne seek)
by the polntes AOosns20
Method
Example

Ren ( testtt )

frread [28)

seek Co) #moves pomtca to tat

tead op) tasain read o28. byte

Renamng
enam flen pytncnu done wis
t
the help'od othe tename C) method The nenameC)
method fatted arquments,
the curent filename Qnd the new cerame

Syntax,!
0.s renome l rent_filename, newflename).
Example

Import os
DS. Tenameesttxt, newtasttt)
lp test ftle Aeramead newesttxt
[Link]") emovel 0S.
Example
(tilename) oeno
re OS.
Syntmx
eut
tilname the fakes Dtdeleted
e catargum og an
tenameas
metnod
ZE the o help the coitn
lones Deletins
a
pelettag
OheneI an Enceptin occurs n pytnon,it stop:
the cumentprDcess and paksespt to the
Until. ft ishardled.
Callinpoces
Progrom fhat Can handle theexception
then the po q94m
y excep
yntax

ty
the he opesatte) 0hich canbe caL4e Crccptbohe,

ercept Exce ptrimt :


thcy excephin2 , eXecute this

exce pt Excep-ton 2!
Cxeprfon2 , ertute tru
else
OCCLrS
ExOmpe

ty
fie =openest tyt", w)
Ale coxfe Chelo Pythoo'")
exCept TOEror :
pYnt
prat Eror? Cannot ird tle or read data
ele
peint (" ontent iaitten suceeE hily
Hlecoe ( ) i

except No Exrephos

The 3tatemeusf that c CALte exCEpTm.S

L xLepstin OCclvserecee te th

ele exeute toc


D
Exomple:

a nt input (" Entes an


dfr = o/a

prInEror 0ccured')
prir pleae eate alid nput)
ele
Pent Div'stn= , di)

8 Cxtept Mutple£xception 3

tyi the opesatm ohich can Cauye exceptohex


whch

except Exceptim 1, xeptn&y -):


L any of the Excepthin DecUsA hrom the hove
ele
eXtcuute tnt
ereLute, alay finally'i
hek
--ecepton cauy can hiOPEXato
ch the tyi
Sytax
finalyi ty
A
else
Dcured Excephim pnt(
EofEror) DOEror, ercept
(
dead) 4-
Example
Example

ty
X= int (inpu Ente intejer "")s

ctir d uto myfie


20s0DrVIenbro

cdorut enteL o
psur /" pleay do)N
fiely close )

You might also like