Professor Donald J. Patterson - Converting File...

Post on 08-Sep-2020

3 views 0 download

Transcript of Professor Donald J. Patterson - Converting File...

Converting File Input •  Aswiththeinputfunc.on,thereadline()methodcanonlyreturnstrings

•  Ifthefilecontainsnumericaldata,thestringsmustbeconvertedtothenumericalvalueusingtheint()orfloat()func.on:

10/17/16

value=float(line)

Page 15

•  Thenewlinecharacterattheendofthelineisignoredwhenthestringisconvertedtoanumericalvalue

Writing To A File •  Forexample,wecanwritethestring"Hello,World!"toouroutputfileusingthestatement:

10/17/16

outfile.write("Hello,World!\n")

outfile.write("Numberofentries:%d\nTotal:%8.2f\n"%(count,total))

Page 16

•  Unlikeprint()whenwri.ngtexttoanoutputfile,youmustexplicitlywritethenewlinecharactertostartanewline

•  YoucanalsowriteformaJedstringstoafilewiththewritemethod:

Example: File Reading/Writing •  Supposeyouaregivenatextfilethatcontainsasequenceoffloa.ng-pointvalues,storedonevalueperline

•  Youneedtoreadthevaluesandwritethemtoanewoutputfile,alignedinacolumnandfollowedbytheirtotalandaveragevalue

•  Iftheinputfilehasthecontents32.054.067.580.25115.0

10/17/16 Page 17

Example: File Reading/Writing (2) •  Theoutputfilewillcontain

32.0054.0067.5080.25115.00--------Total:348.75Average:69.75

10/17/16 Page 18

Example One •  Openthefiletotal.py

10/17/16 Page 19

Common Error •  BackslashesinFileNames

•  WhenusingaStringliteralforafilenamewithpathinforma.on,youneedtosupplyeachbackslashtwice:

10/17/16

infile=open("c:\\homework\\input.txt","r")

Page 20

•  Asinglebackslashinsideaquotedstringistheescapecharacter,whichmeansthenextcharacterisinterpreteddifferently(forexample,‘\n’foranewlinecharacter)

•  Whenausersuppliesafilenameintoaprogram,theusershouldnottypethebackslashtwice

Text Input and Output SECTION 7.2

10/17/16 21

Text Input and Output •  Inthefollowingsec.ons,youwilllearnhowtoprocesstextwithcomplexcontents,andyouwilllearnhowtocopewithchallengesthato^enoccurwithrealdata

•  ReadingWordsExample:

10/17/16

forlineininputFile:line=line.rsplit()

Mary had a little lamb

Mary had a little lamb

input output

Page 22

Processing Text Input •  Thereare.meswhenyouwanttoreadinputby:

•  Eachword•  Eachline•  Asinglecharacter

•  Pythonprovidesmethodssuch:read(),split()andstrip()forthesetasks

10/17/16

Processingtextinputisrequiredforalmostalltypesofprogramsthat

interactwiththeuser

Page 23

Text Input and Output •  Pythoncantreataninputfileasthoughitwereacontainerofstringsinwhicheachlinecomprisesanindividualstring

•  Forexample,thefollowingloopreadsalllinesfromafileandprintsthem:

10/17/16

forlineininfile:print(line)

Page 24

•  Atthebeginningofeachitera.on,theloopvariablelineisassignedthevalueofastringthatcontainsthenextlineoftextinthefile

•  Thereisacri.caldifferencebetweenafileandacontainer:•  Onceyoureadthefileyoumustcloseitbeforeyoucaniterateoveritagain

An Example of Reading a File •  Wehaveafilethatcontainsacollec.onofwords;oneperline:

spam

and

eggs

10/17/16 Page 25

Removing The Newline (1) •  Recallthateachinputlineendswithanewline(\n)character•  Generally,thenewlinecharactermustberemovedbeforetheinputstringisused

•  Whenthefirstlineofthetextfileisread,thestringlinecontains

10/17/16 Page 26

Removing The Newline (2) •  Toremovethenewlinecharacter,applytherstrip()methodtothestring:

10/17/16

line=line.rstrip()

Page 27

•  Thisresultsinthestring:

Character Strip Methods

10/17/16 Page 28

Character Strip Examples

10/17/16 Page 29

Reading Words •  Some.mesyoumayneedtoreadtheindividualwordsfromatextfile

•  Forexample,supposeourinputfilecontainstwolinesoftextMaryhadaliJlelamb,whosefleecewaswhiteassnow

10/17/16 Page 30

Reading Words (2) •  Wewouldliketoprinttotheterminal,onewordperline

MaryhadaliJle...

•  Becausethereisnomethodforreadingawordfromafile,youmustfirstreadalineandthensplititintoindividualwords

10/17/16

line=line.rstrip()wordlist=line.split()

Page 31

Reading Words (3) •  Thesplitmethodreturnsthelistofsubstringsthatresultsfromspliengthestringateachblankspace

•  Forexample,iflinecontainsthestring:

10/17/16 Page 32

•  Itwillbesplitinto5substringsthatarestoredinalistinthesameorderinwhichtheyoccurinthestring:

Reading Words (4) •  No.cethatthelastwordinthelinecontainsacomma

•  Ifweonlywanttoprintthewordscontainedinthefilewithoutpunctua.onmarks,wecanstripthosefromthesubstringsusingtherstrip()methodintroducedintheprevioussec.on:

10/17/16

word=word.rstrip(".,?!")

Page 33

Reading Words: Complete Example inputFile=open("lyrics.txt","r")

forlineininputFile:

line=line.rstrip()

wordList=line.split()

forwordinwordList:

word=word.rstrip(".,?!")

print(word)

inputFile.close()

10/17/16 Page 34

Example Two •  Openthefilelyrics.py

10/17/16 Page 35

Additional String Splitting Methods

10/17/16 Page 36

Additional String Splitting Examples

10/17/16 Page 37