StringFormatsFileInput/Output
CS8:IntroductiontoComputerScience,Winter2019Lecture#11
ZiadMatni,Ph.D.
Dept.ofComputerScience,UCSB
Administrative• Hw06–duenextweekMonday(2/25)• LabtimethisweekisforProject
– Dueinthelastweekofclass• Lab06willbeissuednextweek
• MIDTERM#2isCOMINGNEXTWEEK!!!– OnWednesdayFeb.27th– Practiceexamwillbeonwebsitesoon
2/24/19 Matni,CS8,Wi19 2
Midterm#2• What’sgoingtobeonit?– Functions– Conditionals– Loops– StringFormats– FileI/O– RandomNumbers(andotherMathstuff)*
*dependingonhowfarweget
2/24/19 Matni,CS8,Wi19 3
LectureOutline• Usingtheformat()function
• FileInput/Output
2/24/19 Matni,CS8,Wi19 4
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
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?
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
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?
.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
.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.
MoreExamples• GotoyourtextbookandreadthroughalltheexamplesinCh.4.2
• Thereareothertypesofformat• CHECKTHOSEOUTTOO!!!
2/24/19 Matni,CS8,Wi19 11
2/24/19 Matni,CS8,Wi19 12
Files• Mostlyhandledlikeanysequentialdatatype
– What’sanexampleofadatatypethatcanbereadsequentially?
• Filesareasequenceofcharactersiftheyaretextfiles,orasequenceofbitsiftheyarebinaryfile– Whatarebits??
• Canyounamesomecommonfiletypesthataretextual?Orthatarebinary?
2/24/19 Matni,CS8,Wi19 13
WhyUseFiles?4GoodReasons:
• Filesallowyoutostoredatapermanentlyandconveniently!
• Dataoutputthatgoestoafilestaysthereaftertheprogramends– YoucanusuallyviewthedatawithouttheneedofaPythonprogram
• Aninputdatafilecanbeusedoverandoveragain– Noneedtotypedataagainandagainfortesting
• Filesallowyoutodealwithlargerdatasets– ImagineputtingallhistoricalweatherdatafortheUSAinonelistorstring!!!K
2/24/19 Matni,CS8,Wi19 14
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
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
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
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!
YOURTO-DOsq HW6(dueonMonday,2/25)
q WorkonyourProjectAssignment!
2/24/19 Matni,CS8,Wi19 19
2/24/19 Matni,CS8,Wi19 20