Python Programming: An Introduction to Computer Science

(Nora) #1
4.5.FILEPROCESSING 55

infile = open(someFile,’r’)
for i in range(5):
line = infile.readline()
print line[:-1]


Noticetheuseofslicingtostripoff thenewlinecharacterat theendoftheline.Sinceprintautomatically
jumpstothenextline(i.e.,it outputsa newline),printingwiththeexplicitnewlineattheendwouldputan
extrablanklineofoutputbetweenthelinesofthefile.
Asanalternative toreadline, whenyouwanttoloopthroughallthe(remaining)linesofa file,you
canusereadlines. Thisoperationreturnsa sequenceofstringsrepresentingthelinesofthefile.Used
withaforloop,it is a particularlyhandywaytoprocesseachlineofa file.


infile = open(someFile,’r’)
for line in infile.readlines():


process the linehere


infile.close()


Openinga fileforwritingpreparesthatfiletoreceive data.If nofilewiththegivennameexists,a new
filewillbecreated.Awordofwarning:if a filewiththegivennamedoesexist,Pythonwilldeleteit and
createa new, emptyfile.Whenwritingtoa file,make sureyoudonotclobberany filesyouwillneedlater!
Hereis anexampleofopeninga fileforoutput.


outfile = open("mydata.out", "w")


We canputdataintoa file,usingthewriteoperation.

.write()

Thisis similartoprint, exceptthatwriteis a littlelessflexible. Thewriteoperationtakesa single
parameter, whichmustbea string,andwritesthatstringtothefile.If youwanttostarta new lineinthefile,
youmustexplicitlyprovidethenewlinecharacter.
Here’s a sillyexamplethatwritestwo linestoa file.


outfile = open("example.out", ’w’)
count = 1
outfile.write("Thisis the first line\n")
count = count + 1
outfile.write("Thisis line number %d" % (count))
outfile.close()


Noticetheuseofstringformattingtowriteoutthevalueofthevariablecount. Ifyouwanttooutput
somethingthatis nota string,youmustfirstconvertit;thestringformattingoperatoris oftena handywayto
dothis.Thiscodewillproducea fileondiskcalled“example.out”containingthefollowingtwo lines:


This is the first line
This is line number 2


If “example.out”existedbeforeexecutingthisfragment,it’s oldcontentsweredestroyed.


4.5.3 ExampleProgram:BatchUsernames


To seehowallthesepiecesfittogether, let’s redotheusernamegenerationprogram. Ourpreviousversion
createdusernamesinteractivelybyhavingtheusertypeinhisorhername.If weweresettingupaccountsfor
a largenumberofusers,theprocesswouldprobablynotbedoneinteractively, butinbatchmode.Inbatch
processing,programinputandoutputis donethroughfiles.
Ournewprogramisdesignedtoprocessa fileofnames. Eachlineoftheinputfilewillcontainthe
firstandlastnamesofa newuserseparatedbyoneormorespaces. Theprogramproducesanoutputfile
containinga lineforeachgeneratedusername.

Free download pdf