CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13...
Transcript of CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13...
FileInput/OutputCS8:IntroductiontoComputerScience,Spring2019
Lecture#12
ZiadMatni,Ph.D.Dept.ofComputerScience,UCSB
Administrative• Homework#6–willbepostedtonight:duenextTuesday• Lab05–dueonSundaybymidnight(11:59pm)onGradescope!
• ProjectLabdescriptionisnowup!– Projectcountsas2labgrades– Dueattheendofthequarter(June2nd)
• MidtermExam#2isonMay23rd– Moreinformation/prepmaterialwillbeforthcomingonPiazza
• TherewillNOTbealectureonThursday,May16th5/14/19 Matni,CS8,Sp19 2
ReviewingYourMidterm#1Exam• Optional,butrecommendedforyoutounderstandyour
mistakes
• Ifyou’reinthe8AMlab–gotoChongLiu’sofficehours• Ifyou’reinthe9AMlab–gotoBrianYoung’sofficehours• Ifyou’reinthe10AMlab–gotoShaneMasuda’sofficehours• Ifyou’reinthe11AMlab–gotoProf.Matni’sofficehours
5/14/19 Matni,CS8,Sp19 3
WhenReviewingYourExams(IMPORTANT!)
• Donottakepictures,donotcopythequestions• Youcanonlyviewtheexamduringofficehours• Youcannottaketheexamwithyou• TAcannotchangeyourgrade
– Ifyouhavealegitimatecaseforgradechange,theprof.willdecide– Legitimatecase=Whenwegraded,weaddedthetotalpointswrong– Notlegitimatecase=
“WhydidyoutakeoffNpointsonthisquestion????”
5/14/19 Matni,CS8,Sp19 4
5/14/19 Matni,CS8,Sp19 5
LectureOutline• Quickreviewofrandomnumbers,others
• FileInput/OutputinPython
5/14/19 Matni,CS8,Sp19 6
RandomNumbers• “Pseudo-random”valuescanbegeneratedusingspecialfunctions
inmostprogramminglanguages
• InPythonusefunctionsoftherandommodule– Youhavetoimportrandomfirst
• Simplestwaytomakearandomnumber:random.random()– Returnsafloatingpointvaluebetween0.0and1.0
5/14/19 Matni,CS8,Sp19 7
RandomNumbers• Also:randrange(n),randint(low,high)andmanyothers
– randrange(n) returnsintrandomnumberbetween0andn-1
– randint(low,high)returnsintrandomnumberbetweenlowandhigh(inclusive)
• Trytypinghelp(random)inIDLEtolearnmore…– Andplayaroundwithit
5/14/19 Matni,CS8,Sp19 8
OneMoreNoteonnamedtuple()• Sincetuplesareimmutable,
youcannotchangepartsofthemoncetheyaredefined– Youcanonlyre-assignthewholething
• Forexample:…Mything=Item(item1=42,item2=99)print(Mything.item1) #prints42Mything.item1=0 #DOESNOTWORK!!!LMything=Item(item1=0,item2=99) #WORKS!JJMything=Item(item1=0)#DOESNOTWORK!L5/14/19 Matni,CS8,Sp19 9
Wecangetdatafromafileinputandpresentdatatoafileoutput…
5/14/19 Matni,CS8,Sp19 10
STANDARDINPUT
STANDARDOUTPUT
PROGRAMFILEINPUT
FILEOUTPUT
vs.
Insteadofgettingdatafromastandardinput(i.e.keyboard)andpresentingdatatoastandardoutput…
Files• Mostlyhandledlikeanysequentialdatatype
• What’ssomeexamplesofdatatypesthatcanbereadsequentially?
• Filesareasequenceofcharactersiftheyaretextfiles, orasequenceofbitsiftheyarebinaryfile
• Canyounamesomecommonfiletypesthataretextual?Orthatarebinary?
5/14/19 Matni,CS8,Sp19 11
WhyUseFiles?4GoodReasons:
1. Filesallowyoutostoredatapermanentlyandconveniently!
2. Dataoutputthatgoestoafilestaysthereaftertheprogramends– YoucanusuallyviewthedatawithouttheneedofaPythonprogram
3. Aninputdatafilecanbeusedoverandoveragain– Noneedtotypedataagainandagainfortesting
4. Filesallowyoutodealwithlargerdatasets– ImagineputtingallhistoricalweatherdatafortheUSAinonelistorstring!!!K
5/14/19 Matni,CS8,Sp19 12
Recall:OrganizationofFilesinaComputer
5/14/19 Matni,CS8,Sp19 13
/bin/usr /f2c.exe
/usr/share/doc/faq.txt
IsdonehierarchicallyUsesfolders(akadirectories)Startsatthe“root”directory
designatedwitha/
HowdoIdesignatethisfileusingthefull
directory“path”?
rootà
“parent”
“child”
../meansparenttothecurrentdir
./meanscurrent
FileI/O:SimpleExamplesinfile=open('DataFile.txt','r')line=infile.read() #readeverythinginonestring!#Yes:thereareotherways…print(line)infile.close()#DON'TFORGETTOCLOSE!!!
outfile=open('MyOuts.txt','w')x=3y=4n=(x+y)**youtfile.write('Number'+str(n))outfile.close()#DON'TFORGETTOCLOSE!!!
5/14/19 Matni,CS8,Sp19 14
ExampleofREADINGfromafile ExampleofWRITINGtoafile
WhatyouwriteinafileHAStobea
stringtype
DifferentWaysofReadingFileInputline=infile.read()
#Readeverythinginto1stringline=infile.read(n)
#Readthefirstncharsinto1stringline=infile.readline()
#Read1line(endsin'\n')into1stringline=infile.readlines()
#Readalllinesinto1list
5/14/19 Matni,CS8,Sp19 15
DEMO!Let’stryit!
FileI/O:MoreExamplesfilename=input("Whatisthenameofthefiletoopen?")InFile=open(filename,'r')count=0forlineinInFile:
count+=1print(line)
print("Thereare",count,"linesinthefile",filename)InFile.close()
filename=input("Whatisthenameofthefiletoopen?")OutFile=open(filename,'w')newl='\n'forninrange(10):
OutFile.write('Number'+str(n)+newl)
OutFile.close()
5/14/19 Matni,CS8,Sp19 16
ExampleofREADINGfromafile ExampleofWRITINGtoafile
ReadFilefilename=input("Whatisthenameofthefiletoopen?")InFile=open(filename,'r')count=0forlineinInFile:
count+=1print(line)
print("Thereare",count,"linesinthefile",filename)InFile.close()
5/14/19 Matni,CS8,Sp19 17
ExampleofREADINGfromafile
open()function,usingthe‘r’optionmeansthatwewanttoREADthisfile.Notethatfilenameisastring.
Thisiswhatwe’redoingtothelinesthatwereadfromthefile.Notethattheuseoftheprint()functionheremeansthattheoutputgoesto“standardoutput”(i.e.yourscreen)
Alwaysclose()thefileafteropeningit!
Alternativeinstruction:InFile=open(filename,'r',encoding='utf-8')
WriteFilefilename=input("Whatisthenameofthefiletoopen?")OutFile=open(filename,'w')forninrange(10):
myFile.write('Number‘+str(n))OutFile.close()
5/14/19 Matni,CS8,Sp19 18
ExampleofWRITINGtoafile
open()function,usingthe‘w’optionmeansthatwewanttoWRITEtothisfile.Notethatfilenameisastring.
Thisisthedatathatwe’recreatingtoputintothefile.Notethattheuseofthewrite()functionheremeansthattheoutputgoesto“fileoutput”(not“standardoutput”)NOTE:ENTRIESHAVETOBESTRINGDATATYPES!!!
Alwaysclose()thefileafteropeningit!
ToResetReadingaFile• Togobacktothestartofafilethat’sbeingread,youcan
infile.close()andinfile.open()again– Assuminginfileistheobjectnameyouusedfortheinputfile…
• Anotherwayistouseinfile.seek(0)
5/14/19 Matni,CS8,Sp19 19
Demonstration• Given:Aninputfilewithinformationonrainfall(ininches)forvarious
geographicallocations.Lookslikethis: Akron25.81 Albia37.65…etc…
• Youhaveto:Createanoutputfilethatreadseachlineandoutputs: Akronhad25.81inchesofrain. Albiahad37.65inchesofrain.…etc…
5/14/19 Matni,CS8,Sp19 20
Seerainfall.pyandrainfall_advanced.py
5/14/19 Matni,CS8,Sp19 21
Akron25.81Albia37.65Algona30.69Allison33.64Alton27.43…etc…
rainfall.txt
readlines()
Listofstrings:[“Akron25.81\n”,“Albia37.65\n”,“Algona30.69\n”,“Allison33.64\n”,“Alton27.43\n”,…etc…
“Akron”and“25.81”,“Albia”and“37.65”,“Algona”and“30.69”“Allison”and“33.64”“Alton”and“27.43”,…etc…
Geteachstringandseparatethetownname
fromtherainfallnumberHowdoIdothat???
Akronhad25.81inchesofrainAlbiahad37.65inchesofrain…etc…
report.txt
…Tobecontinuednextlecture…
5/15/19 Matni,CS8,Sp19 22
YOURTO-DOsq Homework#6dueTuesday,5/21q FinishLab5(turnitinbySunday)q RememberthatthisThursday(5/16),there’sNOlecture
q Don’tforget:welivebythebeach…takeadvantageofit!
5/14/19 Matni,CS8,Sp19 23
5/14/19 Matni,CS8,Sp19 24