20
String Formats File Input/Output CS 8: Introduction to Computer Science, Winter 2019 Lecture #11 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

StringFormatsFileInput/Output

CS8:IntroductiontoComputerScience,Winter2019Lecture#11

ZiadMatni,Ph.D.

Dept.ofComputerScience,UCSB

Page 2: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

Administrative•  Hw06–duenextweekMonday(2/25)•  LabtimethisweekisforProject

–  Dueinthelastweekofclass•  Lab06willbeissuednextweek

•  MIDTERM#2isCOMINGNEXTWEEK!!!–  OnWednesdayFeb.27th–  Practiceexamwillbeonwebsitesoon

2/24/19 Matni,CS8,Wi19 2

Page 3: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

Midterm#2•  What’sgoingtobeonit?–  Functions–  Conditionals–  Loops–  StringFormats–  FileI/O–  RandomNumbers(andotherMathstuff)*

*dependingonhowfarweget

2/24/19 Matni,CS8,Wi19 3

Page 4: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

LectureOutline•  Usingtheformat()function

•  FileInput/Output

2/24/19 Matni,CS8,Wi19 4

Page 5: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

FormattedOutputs•  Youknowthesealready:print(42) #prints42andthenanewline(wow)print(42,"!") #prints'42!'andthenanewline(notethespace)print(42,end="") #prints42WITHOUTanewlinecharacter

•  Expandingontheabove…print(42,end="!") #prints42!WITHOUTanewlinecharacter(noteNOspace!)

2/24/19 Matni,CS8,Wi19 5

Page 6: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

Usingthe.format()FunctionwithStrings•  Youcanprintanoutputwhileyoudefineyourgeneralformat!Example:

hour=12minute=55second=31

Ifyoudothis: '{0}:{1}:{2}'.format(hour,minute,second)Yougetthis: 12:55:31 (it’sastringoutput)

2/24/19 Matni,CS8,Wi19 6Let’s try it out!

Note:the{0}referstohour(the0thargument),the{1}tominute(the1stargument),etc…

THISORDERMATTERS!!

Example,whatwouldhappenifIswitched{0}and{1}inhere?

Page 7: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

Moreon.format()•  YoucandefinehowmanyspacesanobjectoccupieswhenprintedExample:

>>>a=19>>>b=42>>>'{0:3}***{1:5}'.format(a,b) '19***42'

2/24/19 Matni,CS8,Wi19 7

3spaces

5spaces Let’s try it out!

Referstothe0thitem(thatis,variablea)

Referstothetotalnumberofspacesyouwanttoformat

Page 8: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

YETMOREon.format()•  WithstringsinsteadofnumbersExample:

>>>a="Be">>>b="Mine!">>>'{:7}{:>7}'.format(a,b) 'BeMine!'

2/24/19 Matni,CS8,Wi19 8

7spaces

7spaces Let’s try it out!

Save7spacesforvar.aandleftjustifyaPutanyextraspacesAFTERitSave7spacesforvar.bandrightjustifybPutanyextraspacesBEFOREit

Whathappensifyourunoutofspace?Doesit:

a.cutoutthestringtomakeitfit?b.stillprintoutthestringevenif it’slongerthanthespaceformat?

Page 9: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

.format()withFloatingPoints•  Ifyousay,print(100/3),youget:33.333333333333336•  Whatifyouwantedtoinstillsomeprecisiononyourdecimalvalues?Example:

>>>'{:7.3f}'.format(100/3) ’33.333'

2/24/19 Matni,CS8,Wi19 9

7spaces

Let’s try it out!

Save7spacesforthefloatingpoint.Put3numbersafterthedecimalpoint

Page 10: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

.format()withFloatingPointsusingEngineeringNotation

•  Ifyousay,print(100/3),youget:33.333333333333336Example:

>>>'{:10.1e}'.format(100/3) '3.3e+01'

2/24/19 Matni,CS8,Wi19 10

10spaces

Let’s try it out!

Save10spacesforthefloatingpointanduseengineeringnotation.

Page 11: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

MoreExamples•  GotoyourtextbookandreadthroughalltheexamplesinCh.4.2

•  Thereareothertypesofformat•  CHECKTHOSEOUTTOO!!!

2/24/19 Matni,CS8,Wi19 11

Page 12: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

2/24/19 Matni,CS8,Wi19 12

Page 13: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

Files•  Mostlyhandledlikeanysequentialdatatype

–  What’sanexampleofadatatypethatcanbereadsequentially?

•  Filesareasequenceofcharactersiftheyaretextfiles,orasequenceofbitsiftheyarebinaryfile–  Whatarebits??

•  Canyounamesomecommonfiletypesthataretextual?Orthatarebinary?

2/24/19 Matni,CS8,Wi19 13

Page 14: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

WhyUseFiles?4GoodReasons:

•  Filesallowyoutostoredatapermanentlyandconveniently!

•  Dataoutputthatgoestoafilestaysthereaftertheprogramends–  YoucanusuallyviewthedatawithouttheneedofaPythonprogram

•  Aninputdatafilecanbeusedoverandoveragain–  Noneedtotypedataagainandagainfortesting

•  Filesallowyoutodealwithlargerdatasets–  ImagineputtingallhistoricalweatherdatafortheUSAinonelistorstring!!!K

2/24/19 Matni,CS8,Wi19 14

Page 15: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

InputandOutputinComputers•  Inputandoutput(orI/O)are2ofthemaincomponentsofanycomputer

•  TherearedifferenttypesofI/O–  Whatwecall“standardoutput”isusuallythescreen–  Whatwecall“standardinput”isusuallyfromthekeyboard–  ButthereAREotherwaystogetI/O

•  Likeusingfilestowriteto(output)ortoreadfrom(input)

2/24/19 Matni,CS8,Wi19 15

Page 16: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

OrganizationofFilesinaComputer

2/24/19 Matni,CS8,Wi19 16

/bin/usr /f2c.exe

/usr/share/doc/faq.txt

IsdonehierarchicallyUsesfolders(akadirectories)Startsatthe“root”directory

designatedwitha/

HowdoIdesignatethisfileusingthefull

directory“path”?

rootà

“parent”

“child”

../meansparenttothecurrentdir

./meanscurrent

Page 17: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

FileI/O:SimpleExampleinfile=open('DataFile.txt','r')line=infile.read() #readeverythinginonestring!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!!!

2/24/19 Matni,CS8,Wi19 17

ExampleofREADINGfromafile ExampleofWRITINGtoafile

Page 18: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

DifferentWaysofReadingFileInputline=infile.read()

#Readeverythinginto1stringline=infile.read(n)

#Readthefirstncharsinto1stringline=infile.readline()

#Read1line(endsin'\n')into1stringline=infile.readlines()

#Readalllinesinto1list

2/24/19 Matni,CS8,Wi19 18

DEMO!Let’stryit!

Page 19: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

YOURTO-DOsq  HW6(dueonMonday,2/25)

q  WorkonyourProjectAssignment!

2/24/19 Matni,CS8,Wi19 19

Page 20: String Formats File Input/Output · – What we call “standard output” is usually the screen – What we call “standard input” is usually from the keyboard – But there ARE

2/24/19 Matni,CS8,Wi19 20