24
File Input/Output CS 8: Introduction to Computer Science, Spring 2019 Lecture #12 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

FileInput/OutputCS8:IntroductiontoComputerScience,Spring2019

Lecture#12

ZiadMatni,Ph.D.Dept.ofComputerScience,UCSB

Page 2: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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

Page 3: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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

Page 4: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

WhenReviewingYourExams(IMPORTANT!)

•  Donottakepictures,donotcopythequestions•  Youcanonlyviewtheexamduringofficehours•  Youcannottaketheexamwithyou•  TAcannotchangeyourgrade

–  Ifyouhavealegitimatecaseforgradechange,theprof.willdecide–  Legitimatecase=Whenwegraded,weaddedthetotalpointswrong–  Notlegitimatecase=

“WhydidyoutakeoffNpointsonthisquestion????”

5/14/19 Matni,CS8,Sp19 4

Page 5: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

5/14/19 Matni,CS8,Sp19 5

Page 6: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

LectureOutline•  Quickreviewofrandomnumbers,others

•  FileInput/OutputinPython

5/14/19 Matni,CS8,Sp19 6

Page 7: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

RandomNumbers•  “Pseudo-random”valuescanbegeneratedusingspecialfunctions

inmostprogramminglanguages

•  InPythonusefunctionsoftherandommodule–  Youhavetoimportrandomfirst

•  Simplestwaytomakearandomnumber:random.random()–  Returnsafloatingpointvaluebetween0.0and1.0

5/14/19 Matni,CS8,Sp19 7

Page 8: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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

Page 9: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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

Page 10: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

Wecangetdatafromafileinputandpresentdatatoafileoutput…

5/14/19 Matni,CS8,Sp19 10

STANDARDINPUT

STANDARDOUTPUT

PROGRAMFILEINPUT

FILEOUTPUT

vs.

Insteadofgettingdatafromastandardinput(i.e.keyboard)andpresentingdatatoastandardoutput…

Page 11: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

Files•  Mostlyhandledlikeanysequentialdatatype

•  What’ssomeexamplesofdatatypesthatcanbereadsequentially?

•  Filesareasequenceofcharactersiftheyaretextfiles, orasequenceofbitsiftheyarebinaryfile

•  Canyounamesomecommonfiletypesthataretextual?Orthatarebinary?

5/14/19 Matni,CS8,Sp19 11

Page 12: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

WhyUseFiles?4GoodReasons:

1. Filesallowyoutostoredatapermanentlyandconveniently!

2. Dataoutputthatgoestoafilestaysthereaftertheprogramends–  YoucanusuallyviewthedatawithouttheneedofaPythonprogram

3. Aninputdatafilecanbeusedoverandoveragain–  Noneedtotypedataagainandagainfortesting

4. Filesallowyoutodealwithlargerdatasets–  ImagineputtingallhistoricalweatherdatafortheUSAinonelistorstring!!!K

5/14/19 Matni,CS8,Sp19 12

Page 13: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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

Page 14: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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

Page 15: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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!

Page 16: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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

Page 17: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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')

Page 18: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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!

Page 19: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

ToResetReadingaFile•  Togobacktothestartofafilethat’sbeingread,youcan

infile.close()andinfile.open()again–  Assuminginfileistheobjectnameyouusedfortheinputfile…

•  Anotherwayistouseinfile.seek(0)

5/14/19 Matni,CS8,Sp19 19

Page 20: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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

Page 21: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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

Page 22: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

…Tobecontinuednextlecture…

5/15/19 Matni,CS8,Sp19 22

Page 23: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

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

Page 24: CS8 Lecture12 FileIO · Recall: Organization of Files in a Computer 5/14/19 Matni, CS8, Sp19 13 /usr /bin /f2c.exe /usr/share /doc /faq.txt Is done hierarchically Uses folders (aka

5/14/19 Matni,CS8,Sp19 24