We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 19
Topics
Working with files : Files, opening and closing a file, working with text files
containing strings, knowing whether a file exists or not, working with binary
files, the ‘with’ statement, the seek() and tell() methods, random accessing of
binary files, zipping and unzipping files, working with directories, running other
programs from python program.1 Table of Contents
4-410 1-17,
11 Piles. 14
12 Opening and Closing a FUE wnnsmsssnsnnenni
1.21 The open() Function... ro
122 Theclose() Function... a
1.3. Working with Text Files Containing Strings...
L4 Knowing Whether a File Exists oF Not mw
LS Working with Binary FlleSen-snmnnnnn
15.1 The ‘with’ Statement... 7 18
16 The seek) and tell() MethodSeenrenernnnnnennnn
16.1 tell) Method. =
162 seek() Method... :
1.7 Random Accessing of Binary Fil€Smmnnnnmn
18
19 Working with Directories nmunnnnsnnnn
1.10 Running other Programs from Python Program wvcsumenunvorsnnen 1.45WORKING WITH FILES
4
Working with es Fes. opeing and losing afl, working with tet fles containing sings knowing whether
a fle exits or nt, working with binary fies, the wih’ statement, the seeKD and tell) methods, random
accessing of binary files, ppg and unzipping les, working with directories, running other program from
python program
11_Flles
“+ Wewereprovousy geting input from the console and writing it ack to the terminal in order to communicate
‘+ tisnotalways suicien to jst splay the data onthe console. The ata to be presented maybe quite vast. and
only limited amount of dats may be displayed onthe contle since memory i volte, making hard to
restore the programmatically creted data repeatedly.
‘+ When data must be saved permanently nfl, le handing is cxtca. A fle designated loeation on ise
‘were associated information is stored. Afr the application has terminated, we may reteve the saved
Information non-olti)
‘+The leaning implementation in he other programming language i significantly longer or moe dia
but tissimpler and shorter in Python,
‘+ ImPytho, les are handed in one of wo ways: text or binary. The fle canbe intext or binary format and ech
ae end withthe speci character.
‘+ Python providing diferent functions for reading writing and accessing the information from directories.
‘These functions are important beczuse al the inportant programs seth les for reading the Input and for
storing the ouput
‘+ Pyton shaving ich cllecton of the input ad the output incon. Python provides the il anctions hike:
1. Opero 2 Chose
3 Read 4 writen)
5. Renamed) 6 Remove1.2 Opening and Closing a Fil
ing UBC Coy
‘There are diferent types of motes are used while opening a fle. The table shows the modes and there
escription
temodes | description
. ‘Thee is opened in readonly mode andthe le pontere placed athe staf the fle Reads
the delat mode
s ‘The files opened both read and write mode. The le pointers placed a the tart ofthe ile
® ‘The les opened in read only in binary format mode. The file pointe is placed atthe tart of
‘he Me Thisis the deft mod
b+ | Thefles are opened in both read and writ in binary format mode. The file pointers placed at
thestart ofthe fie
|= ‘The Mes opened inthe write only mode I the ile is exist Roverites the Me otherwise
creates anew fle for wring
| we | Me eis opened in both read and write mode, Ifthe fle Is exist it overrites the Ale
I otherwise treats anew file for writing as wll as or reading.
wo | The Ales opened for writing only in binary format the fei exis overwrttes the fe,
otherwise rents anew file for writing
[woe | tees open in both write and readin binary format mode. the leis exst it overwrites
the ile, otherwise tereter 3 new efor writings wellas or reading
a ‘Te flee opened n append in binary format mode the lei exist then the file plate is at
the end ofthe file andthe ie i in the append mode I thee does nt ens creates a new
Ae for writing
- “The file is open in both the read and append mode. the fle is exit then the le pote sat
the end ofthe ile andthe le ii the append mode I the Rl does not ens creates new
efor writing a wel as for reading.
ay “The lei opened in append in binary format mode Ifthe fie exist then the fle pointers at
the end ofthe fle andthe fies inthe append mode. he fle doe not exist, reates 3 new
fle for wet
abe [The les open in both the append and red in binary format mode I the Mle sexist then the
fle pointer iat the endo the land the leisin the append mode the file doesnot ett,
creates anew file for wring 38 wells for reading.Mest ofthe le manipulation operations are performed by sing thei obet
ample
ova pent mle
ere noting but he le bjt Open earns He abe.
121 The opend Function
When youread and wrt ts important to ope st. To pen the fl Python's bln open function
ed
The open function creates fle object where ti le jets sed to cll other support methods associated
waaemegmanetbespnfnctonisnfiiowes
Flename |The le name parameter ifr the name cf the ie which you are going to acces
‘This parameter e mandatory. eg abet
‘Acces Mede | Ths parameter optional. The default fl acess model read. Theses mode
species the mode ofthe fin wichita o ope ke read were, append et.
‘fering _| The butering parametric optional the value of baller:
No betering
‘Thelin buena arid ou for acesing the
t+ bulleringis performed withthe inaeatdbuer se
_or-ve the buf sizes the yrtom dealt
Syma
‘leche = pene name [access mode bute)
Example
‘+ Thefolowing example shows that he le object eeated a fede which eFand then he open function ie
sed with arguments the le name andthe file mode
>>> feopen("'sample. txt", "2")
>>
‘+ you want to open ale and excite the blk of code then open sing the With keyword and use “esto
eine the varlable. inthis instead of defnng he fle cet at et sie we are dering itt the ightside
rr[ a
wins? i ae
Sredite” or "itcense()® for more infor
Sy etin opentrabe. txt, *eyae £:
‘print (f mode)
1.2.2 The closed Function
+ Tetle objets close) method Mush out any unwritten information and cote the le obec.
Once the fil is closed then no more writing can be done, The file i dosed automatically n Python when the
reference object ofa ies reassigned to another
‘+ Butts proposed to use the close function to elas the lea a good practice.
Syntax
Aleobjecttose(
ample
‘Be Geely Optom Windows Hep
bop thecbsece opens
2p peels. *, Bdeobeer sam)
>> taleabject.ciove()
Working with Text Files Containing Strings
‘There are wo types files, text and binary. The text Mesa structure fle which contains the sequence of ies
‘The ines are the sequence of characters, The En of Line (EDL) character is wed to terminate the ln. Newine
Comma) isthe mast common ine terminators.
“Totreatthe netting as new lin the backslash characters used. Abinary fle any fle which doesnot contain
‘The binary files reprocessed bythe applications who know the les structure.
+ Read) and write) are the two secess methods provided bythe Me abject.
‘The write method
“The write) method ie used to write any string tan open fl. The Python strings contains binary datas well as
text Anewline character (\n) kenat added atthe end of the string in the write method 0.
——
ering wes
nc yan Pagaing BSC 1s
‘Syren
eobectwetesteng:
ering parameter othing but the content to be writen into the opened Me
example: We He Wott nf
TD owanginrettiepy cies. - OX
Fie ét Format Run Options Window Help
£ = open(‘example.txt',"W') ri
E.write(‘hello world’) Bl
Elclose() a
Le? Coto
[Drcomplent-ciesien. — O x
File Edit Format_Run Options Window Help
j hello world ——-
Ted Cobo
[Ba write uncon example py -C\User\ LENOVO\Ap.
Fle Edt Format Rin Options Window Help _
‘open ("example. txt"
Eweite ("hello world")
flwrite('\n Python Programming")
Elclose)
np
D vaampi Cinen LENOVO App
|e Ede Format fin Options Window Hep
pelle world -
Python Programing
‘The reod9 Method
‘+ Toread the sting from the le the read) method is used. The ser has to ope the le fist forthe reading.
‘Tere are two types of string data avalabl ones the text data and another i bnary dat,
a |ayaa yan Progamming (MULES Cong Ls
‘Sy:
eodjectread (count
+ Thenumber of bytes which we read from an open leis given by the count argument,
1 Thereading ofthe string stats trom the begining ofthe open le. we forget to give the coun hen wn
read as muchas possible texto wil read the ext il the endo he Me
‘Toread the filcontnts ofthe fle he code
Inthe above ode the abe tle opened then read method i used to read the file and file contents ae prin
‘When you done with the reading, then delete the fle object and then close the le So nthe above code th fle
object st
soda
>>> foseD)
1+ Wecanalsoread the le by using he Boek of code. The folowing example shows reading using the Block
1.4__Knowing Whether a File Exists or Not —
‘Python inches an OS module that may be used to interface with the underlying files, folders and directories
‘Toe oxpathisfle) function in Fython maybe used to determine whether airectory anda certain fle ext
am
ie Kt fat fun epi nde
= on.path.istile(parh)
inetsonra 56 Cony 2 wonengoin is
oust:
[a Python 37.7 shet - o x
File Edit Shell Debug Options Window Help
ta/Local/Programs/Python/Python3
7/file exist example.py
True
False
>>I
2L5__Working with Binary Files 0
2 dtl the open Qmetodopes fn te frat. Ad to the mode argument open aes inary
format Asa esl the 18 mode rend the len nary format bt the Ww mode we the fein nay format
Binary es unite tees, cnnatbe ed by humans. The data sunrecognsble when opened ay text etor
‘The code below saves list finer to biaryl Before wing the st stansfrmedtoa byt ary. The
bitin etd byte returns the objects be repesenttin
ample 1:
[ *inan:py- Css LENOVO/BppDaalLocs/Progrmu/Pythen/yhon. — OX
File fa Format Run Options Window Help
fropen(“binfile. bin”, wb")
ire, i
Ua “binftebin - C\Users\LENO.
File Edit Format Run Options Window Help7
Atvnet prac Wering ih ri
ample 2
(B-boy mae yee NOVO Anca romney mage ney D>
Fa an Fema fan tis eden ap
fisopen
Emopen (oe
Syeeretlreeay)
dheriteteyees)
printer tntve au avatiabte with the names wert soy"?
few Shage Sa aaizanze wien the name: newpic. seg
ae
opi -SuchRewinryess? =~ DX
re
mong 6
Hommes ol | fe Om
B tmmens + a
Brae
Waco
sings
15.1 The‘with’ Statement
Python 25 introduces the with statement When working with les, the with statement comes very Iti used
when pir of statements must be performed with a block of code in between. The syntax for opening 2 fe wine
with the statements shown as follows
Syma
‘Meobjectdosevth open cA name>, access mode») as
eratementsune
‘+ The beneito using the with statements that guarantees thatthe file wil be cosed regardless of how tht
Inner back terminates.
‘+ Its generally recommended to use the with statement when dealing with les because if break return. oF
‘exception happens within the nested block of ode mmedately loses the fe, eliminating the need to wait
the close) method, prevents the fle from being corrupt.
rrrsc king wine,
[oe sateen mpc heeNONO
F(t femat fun Spans Wnt ap
‘content = f.read()
_ print (content)
1.6 _ The seek( and tell) Methods
16.1 talQ Method
Syeme
‘tet
‘The el) methods seo determine the current postion within the le nother words, the next ead or wee
wocar at that many byes rom the eganing ofthe fle
+ Teotoming examples tusrate the fe poston.
ample:
printf.
Brine (£. readline ())
Brine (f-e0110)yw 10 meng ihe
en ex
Fie Eat Shel Debug Options Window Help
10 4
2
Programming
16.2 seek Method
Syma
seo (tet, rom)
+ Sometimes there isa nee of changing the current position of the le while doing the programming $0, to
change the current postion of the fle the sot) method i used. There are two arguments of his method fe,
from
+The offic argument indicates the number of bytes tobe moved: The rom argument specifies the reference
postion fom where the bytes are to be moved.
+ from s sto 0, means use the begining ofthe Mle asthe reference postion and 1 means we the cree
postion asthe reference postion and if set to 2 the the end of the le would be taken asthe cefersnce
c=f-read(s)
print (crend=" *)
foseek(0)
cAf.read(s)
print (e)
(a Fenon 377 She
Fle Edt Shel Debug Options Window Hep‘Arann ton Progaming U.S Co
55 sesetowercett|
ge eng sesung 18 mye
oot
1L7_Random. of Binary Files
“+ sing the mmap module lows the wee to randomly access locaton inl by mapping the lent memory,
‘This isan alternative to using normal le operations.
“+ Mesory mapped le objects behave Inthe same way as byteatrye andes Most places where bytearray are
lepected an use mmap objects: for example the re module can be wet search though a memen-mapped
fe Youcan ls change asingle bye by typing obindes] +97, ora subsequence by writing obi] =b'
‘+ -Amemory-mapped leis crested bythe mmap constructor, which diferent on Unixandon Windows neler
‘le, you mst supply a fl descriptor for fle tat has bees opened for updating IF you vant to map an
‘extng Python fe object us its leno method to pet the correct len parameter value, Other, you can
‘open the fle diety withthe osopen)fanction, which returns afl descriptor (the fle still needs to be dosed
when done).
Syme
samapammap(fleno length tagame, aces of)
+ Grates a mmap object by mapping length byes from the fle specified by the Re handle Meno I length is
restr than the current fle sag, he les extended to ncade length bytes. length iO the maxima length
‘ofthe map isthe caren size ofthe fl, unless the fle s empty, In which case Windows throws an exception
(Youcanstcrestean empty mapping en Windows)
+ egpame,fspecied and not None, sting containing the name ofthe maps tag Windows allows you to
‘ave muliple mappings for he same le you ester the nane ofan existing tg it apened otherwise, 3 ne"
‘ag with the sme name is created. The mapping i ceated witht a name his parameter i omited o et
‘+ Avoiding the use of he a parameter wl ad in the porsabty of your ode between Unix and Windows. ofset
‘sa non-negative integer offset that can be spciedmmap references wile entve tothe fet rom th fle’
beponingcftet the default value The ose value must bes multiple ofthe lation Granular
Tee req
Speer
sence !
FSS Sontane ubing mateo notatsons i
A scee'that'nee content mast hate wane size
eh NE s !
Frintimreastine gd) prints oo
[BD Pymens 77S
BY\x80\x03) q\x00 (RROD \x88G0\x07\n"
br\x03}q\x00"
Br\qB0\H03)q\x00 (R\x01\x0868\x07\n"
and Files
‘Te ably tap andunsip files isa very common regulrement. The following are the mala benefits
+ Toincrease memory usage
‘+ Wecan speed up the transfer proce
+ Wenave he abit to improve performance.
Python has a bullt-n mode called zp that allows yout zip and unalp les. This module contains the ZpFle
clas wich we wll us nthe examples
Creating a ZipFile
tn Python. we must first create am object ofthe Zipfle class with the name we wantto give the ip flea wells
‘the mode andthe constant ZIP DEFLATED. Tis constant indlaes that we are making ip Mle
‘Syma:
(phe tesa "2 DEFEATED)
Aer wehave shed retng the ZipFle object, we can use the write method to add fle to (ena).
eee ie=zipFile | pts Sty Be DEFLATED) |
Emcor
moter
‘You can now ok inyour current rectory forthe fle named fles2ip" which shuld be there.
arena =
Pte Set Sng Ope ony ree
Re Seee tor ggcat oat \ropram\ eben yeh? 4
Unspping Mes
Im the same way that we did or ipping the fe, we must create an obec However, the argument values are
Stax:
Zp Ressp "FP STORED)|
em ing M0855 0 1s tes
“The uip operation represented by ZIP STORED. Ti
work,
‘Aer we have crested a Zipfle object for urspping we can we the namlist() method to get ist ofthe Fey
nha i le
bearessaarea __
[seer Comm imovonepourecitapamemtovttenTinwe. — 0
Fa ta fort fin Opty Wadon Hep
toe sipfile iesst *
eetiphile("tiies.sip", ‘x, 219 STORED)
pames=f-namelist ()
SV print ( "rile Name: “yname)
rent we dont spect veh
the dtl
1.9 Working with Directories
Al the fles are kept in various directories. Python can handle the directories too. The module os contains
‘various methods to crete, remove and change director.
1 mkdirg Method
‘The ml) method is used to create new directory Inthe current directory. The mil) method i of OS
‘module Diecnry name the argument which you need to supply.
eee
2, getcwd0 Method
‘The getewd method gies the current working retry
Sy:
osgetewd0
ee-—d2 iremg Su 1 ows
2 eheg Method
“Tee ehh) method is use to change the current rectory. The ch) method takes directory name as an
srprment that you want to make he current etry
2A aan eerreah atnar!
4 imdieg Method
‘Teermir method i sed delete the directory, the etary names pssed a an argumentin the method.
Keepin mind that before removing directory, sll the conensinit shouldbe remove,
‘As you can seen example first ret delete the decor Sarna butt was ot empty sot ried the ever.
‘Next when fll paths vn andthe lretry Is empty got deleted,
1.10 Running other Programs from | Program
‘+ The 0s module providesa number of option fr your programme tolateract with othe programmesw
over the eterna programe,
‘The 0S mada also ncudes number of functions that begin with the later exec. Fine gralned contre i
+ Inthe same proces however. programme run by ane ofthe nee functon replaces the current programme
(Ge. the Python imerpreter
‘= imprecise you wll mostly use the exe functons an platforms that allow a process tofrk and duplicate ele
(G2, nice platform), Final, 0S functions beginning with spawn and popen provide balance of simply
nd power they ae cross-platform and not ql as simple system, but they are simple and usable enugh
foros apricatons
‘The exec and spawn functions run an executable le given its path, arguments to pass it and optionally an
‘The system and popen functions run a command, which i a string passed to the platform's default shel
(csualyot/sh on Una commandcom or cmd.exe on Windows}
‘A command is broader concept than an exacutable file because it can include sell fnetionality (pes,
‘direction and builtin shell commands} while stil adhering tothe platform's standard shell syntax.
‘sample nthe given example we are running the command notepadexe
Dmg pen tempat StmeninoaipaacaltagemiRaNTReRa. =~
fie tat fem Ren Opts ind tpReview Questions
01 Wats te
22 Homo pena fe? Explain wth example.
3. How tocose ate ? Explain with example,
4 How to chock ae one or not 7 Explain wth exams
15 Expain Wi’ statement wth example
(26 Explain seek) and) mathods,
127 Expiain peng and unipping ote,
(28 Expian how torn cher programs trom python program,
‘aoa