Python Programming: An Introduction to Computer Science

(Nora) #1
4.5.FILEPROCESSING 53

Youcanthinkofa textfileasa (possiblylong)stringthathappenstobestoredondisk.Ofcourse,a
typicalfilegenerallycontainsmorethana singlelineoftext.A specialcharacterorsequenceofcharactersis
usedtomarktheendofeachline.Therearenumerousconventionsforend-of-linemarkers.Pythonusesa
singlecharactercallednewlineasa marker.
Youcanthinkofnewlineasthecharacterproducedwhenyoupressthe Enter key onyourkeyboard.
Althougha newlineis a singlecharacter, it is representedinPython(andmany othercomputerlanguages)
usingthespecialnotation’



n’. Otherspecialcharactersarerepresentedusinga similarnotation(i.e.,’

t’
for Tab ).
Let’s take a lookat a concreteexample.Supposeyoutypethefollowinglinesintoa texteditorexactlyas
shownhere.


Hello
World


Goodbye 32


Whenstoredtoa file,yougetthissequenceofcharacters.


Hello\nWorld\n\nGoodbye 32\n


Noticethattheblanklinebecomesa barenewlineintheresultingfile/string.
Bytheway, byembeddingnewlinecharactersintooutputstrings,youcanproducemultiplelinesofoutput
witha singleprintstatement.Hereis theexamplefromabove printedinteractively.





print "Hello\nWorld\n\nGoodbye 32\n"
Hello
World





Goodbye 32








If yousimplyaskPythontoevaluatea stringcontainingnewlinecharacters,youwilljustgettheembedded
newlinerepresentationbackagain.





"Hello\nWorld\n\nGoodbye 32\n"
’Hello\nWorld\n\nGoodbye 32\n’





It’s onlywhena stringis printedthatthespecialcharactersaffecthow thestringis displayed.


4.5.2 FileProcessing


Theexactdetailsoffile-processingdiffersubstantiallyamongprogramminglanguages,butvirtuallyalllan-
guagessharecertainunderlyingfilemanipulationconcepts.First,weneedsomewaytoassociatea fileon
diskwitha variableina program.Thisprocessis calledopeninga file.Oncea filehasbeenopened,it is
manipulatedthroughthevariableweassigntoit.
Second,weneeda setofoperationsthatcanmanipulatethefilevariable.Attheveryleast,thisincludes
operationsthatallow ustoreadtheinformationfroma fileandwritenew informationtoa file.Typically, the
readingandwritingoperationsfortextfilesaresimilartotheoperationsfortext-based,interactive inputand
output.
Finally, whenwearefinishedwitha file,it isclosed. Closinga filemakessurethatany bookkeepingthat
wasnecessaryto maintainthecorrespondencebetweenthefileondiskandthefilevariableis finishedup.For
example,if youwriteinformationtoa filevariable,thechangesmightnotshow uponthediskversionuntil
thefilehasbeenclosed.
Thisideaofopeningandclosingfilesis closelyrelatedto how youmightworkwithfilesin anapplication
programlike a wordprocessor. However, theconceptsarenotexactlythesame.Whenyouopena fileina
programlike MicrosoftWord,thefileis actuallyreadfromthediskandstoredintoRAM.Inprogramming

Free download pdf