54 CHAPTER4. COMPUTINGWITHSTRINGS
terminology, thefileis openedforreadingandthethecontentsofthefilearethenreadintomemoryviafile
readingoperations.Atthispoint,thefileis closed(againintheprogrammingsense).Asyou“editthefile,”
youarereallymakingchangestodatainmemory, notthefileitself.Thechangeswillnotshow upinthefile
onthediskuntilyoutelltheapplicationto“save”it.
Savinga filealsoinvolvesa multi-stepprocess.First,theoriginalfileonthediskis reopened,thistimein
a modethatallowsit to storeinformation—thefileondiskis openedforwriting.Doingsoactuallyerasesthe
oldcontentsofthefile.Filewritingoperationsarethenusedtocopy thecurrentcontentsofthein-memory
versionintothenew fileonthedisk.Fromyourperspective, it appearsthatyouhave editedanexistingfile.
Fromtheprogram’s perspective, youhave actuallyopeneda file,readitscontentsintomemory, closedthe
file,createda new file(havingthesamename),writtenthe(modified)contentsofmemoryintothenew file,
andclosedthenew file.
Workingwithtextfilesis easyinPython.Thefirststepis toassociatea filewitha variableusingthe
openfunction.
Herenameis a stringthatprovidesthenameofthefileonthedisk.Themodeparameteris eitherthestring
"r"or"w"dependingonwhetherweintendtoreadfromthefileorwritetothefile.
Forexample,toopena fileonourdiskcalled“numbers.dat”forreading,wecouldusea statementlike
thefollowing.
infile = open("numbers.dat", "r")
Now wecanusethevariableinfiletoreadthecontentsofnumbers.datfromthedisk.
Pythonprovidesthreerelatedoperationsforreadinginformationfroma file:
Thereadoperationreturnstheentirecontentsofthefileasa singlestring.If thefilecontainsmorethanone
lineoftext,theresultingstringhasembeddednewlinecharactersbetweenthelines.
Here’s anexampleprogramthatprintsthecontentsofa filetothescreen.
printfile.py
Prints a fileto the screen.
def main():
fname = raw_input("Enterfilename: ")
infile = open(fname,’r’)
data = infile.read()
print data
main()
Theprogramfirstpromptstheuserfora filenameandthenopensthefileforreadingthroughthevariable
infile. Youcoulduseany nameforthevariable,I usedinfiletoemphasizethatthefilewasbeingused
forinput. Theentirecontentsofthefileis thenreadasonelargestringandstoredinthevariabledata.
Printingdatacausesthecontentstobedisplayed.
Thereadlineoperationcanbeusedtoreadonelinefroma file;thatis,it readsallthecharactersup
throughthenext newlinecharacter. Eachtimeit is called,readlinereturnsthenext linefromthefile.This
is analogoustorawinputwhichreadscharactersinteractivelyuntiltheuserhitsthe Enter key;each
calltorawinputgetanotherlinefromtheuser. Onethingtokeepinmind,however, is thatthestring
returnedbyreadlinewillalwaysendwitha newlinecharacter, whereasrawinputdiscardsthenewline
character.
Asa quickexample,thisfragmentofcodeprintsoutthefirstfive linesofa file.