Download - Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Transcript
Page 1: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

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

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

10/17/16

value=float(line)

Page 15

•  Thenewlinecharacterattheendofthelineisignoredwhenthestringisconvertedtoanumericalvalue

Page 2: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

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:

Page 3: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

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

•  Youneedtoreadthevaluesandwritethemtoanewoutputfile,alignedinacolumnandfollowedbytheirtotalandaveragevalue

•  Iftheinputfilehasthecontents32.054.067.580.25115.0

10/17/16 Page 17

Page 4: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Example: File Reading/Writing (2) •  Theoutputfilewillcontain

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

10/17/16 Page 18

Page 5: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Example One •  Openthefiletotal.py

10/17/16 Page 19

Page 6: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

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

Page 7: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Text Input and Output SECTION 7.2

10/17/16 21

Page 8: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

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

Page 9: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Processing Text Input •  Thereare.meswhenyouwanttoreadinputby:

•  Eachword•  Eachline•  Asinglecharacter

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

10/17/16

Processingtextinputisrequiredforalmostalltypesofprogramsthat

interactwiththeuser

Page 23

Page 10: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Text Input and Output •  Pythoncantreataninputfileasthoughitwereacontainerofstringsinwhicheachlinecomprisesanindividualstring

•  Forexample,thefollowingloopreadsalllinesfromafileandprintsthem:

10/17/16

forlineininfile:print(line)

Page 24

•  Atthebeginningofeachitera.on,theloopvariablelineisassignedthevalueofastringthatcontainsthenextlineoftextinthefile

•  Thereisacri.caldifferencebetweenafileandacontainer:•  Onceyoureadthefileyoumustcloseitbeforeyoucaniterateoveritagain

Page 11: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

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

spam

and

eggs

10/17/16 Page 25

Page 12: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

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

•  Whenthefirstlineofthetextfileisread,thestringlinecontains

10/17/16 Page 26

Page 13: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

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

10/17/16

line=line.rstrip()

Page 27

•  Thisresultsinthestring:

Page 14: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Character Strip Methods

10/17/16 Page 28

Page 15: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Character Strip Examples

10/17/16 Page 29

Page 16: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Reading Words •  Some.mesyoumayneedtoreadtheindividualwordsfromatextfile

•  Forexample,supposeourinputfilecontainstwolinesoftextMaryhadaliJlelamb,whosefleecewaswhiteassnow

10/17/16 Page 30

Page 17: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Reading Words (2) •  Wewouldliketoprinttotheterminal,onewordperline

MaryhadaliJle...

•  Becausethereisnomethodforreadingawordfromafile,youmustfirstreadalineandthensplititintoindividualwords

10/17/16

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

Page 31

Page 18: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Reading Words (3) •  Thesplitmethodreturnsthelistofsubstringsthatresultsfromspliengthestringateachblankspace

•  Forexample,iflinecontainsthestring:

10/17/16 Page 32

•  Itwillbesplitinto5substringsthatarestoredinalistinthesameorderinwhichtheyoccurinthestring:

Page 19: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Reading Words (4) •  No.cethatthelastwordinthelinecontainsacomma

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

10/17/16

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

Page 33

Page 20: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

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

Page 21: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Example Two •  Openthefilelyrics.py

10/17/16 Page 35

Page 22: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Additional String Splitting Methods

10/17/16 Page 36

Page 23: Professor Donald J. Patterson - Converting File Inputdjp3.westmont.edu/classes/2016_09_CS010/Lectures/Lecture...ch07.pptx Author Donald Patterson Created Date 10/17/2016 5:49:57 PM

Additional String Splitting Examples

10/17/16 Page 37