Open, read, write and close file

CompSci101-PrinciplesofProgramming
2
Learningoutcomes
! Attheendofthislecture,studentsshouldbeableto:
!  understandthefilesystemstructure
!  openandcloseafile
!  writedatatoafile
!  readdatafromafile
COMPSCI11
PrinciplesofProgramming
!  InCompSci101wearedealingwithtextfilesonly.
Lecture19–Open,read,writeandclosefiles
CompSci101-PrinciplesofProgramming
3
CompSci101-PrinciplesofProgramming
Recap
! Fromlecture18:completethecarry_out_transacLons()funcLonwhichis
passedaniniLalbalanceandatupleoftransacLons(posiLveandnegaLve
amounts).ThefuncLonreturnsatuplemadeupofthreevalues:thefinal
balance,thesumofallthedepositsandthesumofallthewithdrawals.
4
Programdata
! Datausedinaprogramistemporary,andislostwhenthe
programterminates.
def carry_out_transactions(balance, transactions_tuple):!
!withdrawals = 0!
deposits = 0!
for trans in transactions_tuple:!
! !if trans < 0:!
! ! !withdrawals += abs(trans)!
! !elif trans > 0:!
! ! !deposits += trans!
!
Balance$4950,deposits$1250,withdrawals$1700
! !balance += trans!
return (balance, deposits, withdrawals)!
def main():!
!results = carry_out_transactions(5400, (100, -400, 500, !
-800, 600, -100, - 200, 50, 0, -200))!
import random!
!
def main():!
!my_list = []!
!for num in range(20):!
! !my_list = my_list + [random.randrange(10, 100)]!
!print(my_list)!
!
main()!
[67,53,35,39,89,44,73,86,48,69,74,97,60,64,72,56,88,80,39,69]!
!
!
!print("Balance $", results[0], ", deposits $", results[1], !
", withdrawals $", results[2], sep="")!
main()!
! Topermanentlystorethedatacreatedinaprogram,we
needtosaveitonaphysicalstoragedevice.
CompSci101-PrinciplesofProgramming
5
6
CompSci101-PrinciplesofProgramming
Files
Accessingafile
! WhenaconnecLonhasbeensetupbetweenaPython
programandafile,a'streamofdata'isestablished
betweenthetwo:
! AfileisacollecLonofbytesofinformaLonthatusually
residespermanentlyonadisk.
! Thedatainafilecanbeusedlaterbyotherprograms.
! AccessingafilemeansestablishingaconnecLonbetween
thefileandaprogramandmovingdatabetweenthetwo.
! Weneedtobeableto:
! readdatafromafileintoaprogram
! writedatafromaprogramtoafile
CompSci101-PrinciplesofProgramming
7
CompSci101-PrinciplesofProgramming
Accessingafile
! Thefilesystemofacomputerorganises
filesinahierarchical(tree)structure.
! filesareplacedinsidedirectories.Directories
cancontainfilesorotherdirectories.
Python3
! AcompletedescripLonofwhichdirectoriesto
visitinordertoreachacertainfileiscalleda
path,e.g.,
! Thefilepathisthe'\'separatedlistofdirectorieswhich
needtobevisitedinordertoreachthefile.Forexample,if
theinput.txtfileneedstobeaccessed
frominsidetheprog2.pyprogram,itcan
C:
beaccessedbytheabsolutepath:
Python3
Users
'C:/Users/Adriana/Documents/input.txt'!
Adriana
orbytherelaRvepath:
C:
Users
Adriana
Documents
C:/Users/Adriana/Documents/prog1.py!
Eachpathtoafileoradirectorymustbe
unambiguous.
prog1.py
prog2.py
8
Pathofafile
Documents
input.txt
'input.txt'!
prog1.py
prog2.py
input.txt
CompSci101-PrinciplesofProgramming
9
CompSci101-PrinciplesofProgramming
Binaryvstextfiles
! Pythonfilesareclassifiedintotwocategories,i.e.,textand
binary.
! textfilescanbeprocessedusingatexteditor.
! binaryfiles,e.g.,images,audio,videofilesaredesignedtoberead
byspecialapplicaLonswhich'understand'theirformat.
! Ifyouopenabinaryfileusingatexteditor,theeditortriesto
matchthebinaryinformaLontotextcharactersbutmostlythefile
informaLonwillbegobbledygook.
10
Processingfiles
! TousePython'sbuiltinfileprocessingfuncLonsyoumust
firstopenthefile.Onceopen,datawithinthefileis
processedusingfuncLonsprovidedbyPython,andfinally
thefileisclosed.Alwaysremembertoclosethefilewhen
you'redonesothattheresourcescanbereleased.
Imagefiledisplayedbyatexteditor
Samefiledisplayedbyanimageviewer
CompSci101-PrinciplesofProgramming
11
CompSci101-PrinciplesofProgramming
Openingafile
! ThePythonsyntaxforopeningafileis:
file_variable= open(filename, mode)
!!
Thevariable,file_variable,isnowtheconnecLonbetween
theprogramandthefile,andthisvariablecannowbe
usedtoread/writetothefile.
! Forexample:
defmain():
input_file = open("stocks.txt", "r")
main()
!!
Notethatthefilenameisthepathofthefile.Inthiscasethefile,"stocks.txt"isinthesame
directoryastheprogram,i.e.,thefilepathusedistherelaRvepath.
12
Fileaccessmodes
! ThePythonsyntaxforopeningafileis:
file_variable= open(filename, mode)
!!
Mode DescripRon
'r' Opensafileforreading.
'w' OpensafileforwriLng.
#ThefollowingmodesarenotusedinCompSci101
'a' Opensafileforappendingdata.Dataiswri_entotheendofthefile.
'rb' Opensafileforreadingbinarydata.
'wb' OpensafileforwriLngbinarydata.
CompSci101-PrinciplesofProgramming
13
CompSci101-PrinciplesofProgramming
Closingafile
! First,thefileneedstobeopenedforwriLng:
! ThePythonsyntaxforclosingafileis:
!  Iftheoutput.txtfiledoesnotexistthentheopen()funcLoncreatesthefile.
!  Iftheoutput.txtfileexiststhentheopen()funcLonerasesthecontentsofthe
file.
! Theclose()methodclosesthefile(i.e.,releasesthefile
resources).A`erafilehasbeenclosed,accesstothefile
contentsisnolongeravailableunLlthefileisopened
again.
!  ThesyntaxforwriLngtoafile:
! Ifthemodeiswritemode,thenanyasyetunwri_encontentisflushedto
thefile.
output_file = open("output.txt", "w")!
file_variable.close()!!
! Forexample:
defmain():
input_file = open("stocks.txt", "r")
#processthefile
input_file.close()
!  Forexample:
output_file.write(a_string_of_text)!
defmain():
output_file = open("output.txt", "w")!
output_file.write("She walks in beauty, like the night\n")
output_file.write("Of cloudless climes and starry skies\n")
output_file.write("\nLord Tennyson")
output_file.close()
main()
!!
main()!!
CompSci101-PrinciplesofProgramming
15
CompSci101-PrinciplesofProgramming
WriLngtoafileconLnued
!  ThesyntaxforwriLngtoafile:
output_file.write(a_string_of_text)!
andtheparameterpassedtothewrite()funcLonisa
string.Anynumbersneedtobeconvertedusingthestr()
funcLon.Anynewlinesneedtobewri_entothefile
("\n").Forexample:
def main():!
!output_file = open("output.txt", "w")!
!sum_of_nums = int(input("Enter num: "))!
!sum_of_nums += int(input("Enter num: "))!
!output_file.write(str(sum_of_nums) + "\n")!
!output_file.close()!
!
main() !!
14
WriLngtoafile
16
Programwith3errors
! Findthethreeerrorsinthefollowingcode.Thefilewhich
shouldbecreatedbythefollowingcodeisshownbelow:
defthree_errors(list1):
output_file=open("oops.txt","w")
fornuminlist1:
output_file.write(num)
defmain():
a_list1=[2,4,5,6,8,1]
three_errors(a_list1)
main()!!
CompSci101-PrinciplesofProgramming
17
CompSci101-PrinciplesofProgramming
CompletethefuncLon
! Completethewrite_to_file()funcLonwhichwritesthe
elementsofthetwoparameterlists(oneelementfrom
bothfilesperline)tothefile(givenbytheparameter,
filename).Theelementsareseparatedby":".
def write_to_file(filename, list1, list2):
18
Readingafile
! First,thefileneedstobeopenedforreading:
input_file = open("input.txt", "r")!
Iftheinput.txtfiledoesnotexistthenanerroroccurs.
Assumethetwofileshaveexactly
thesamenumberofelementsand
thateachelementisaninteger.
!  Thefourwayscharacterscanbereadfromafile:
def main():
a_list1 = [2, 4, 5, 6, 8, 1]
a_list2 = [123, 54, 58, 106, 87, 206]
filename = "combined_lists.txt"
write_to_file(filename, a_list1, a_list2)
input_file.read()!
input_file.read(an_integer)!
input_file.readline()!
input_file.readlines()!
main()!!
CompSci101-PrinciplesofProgramming
19
CompSci101-PrinciplesofProgramming
Theread()funcLons
! Theread()methodreturnstheenLrecontentsofthefile.
Thismethodreturnsastring.
all_contents = input_file.read()!
! Theread(an_integer)methodreturnsthespecified
numberofcharacters(astring)fromthefile.
some_characters = input_file.read(an_integer)!
20
Theread()funcLons-examples
! BoththefollowingsecLonsofcodeusethefilebelow:
input_file=open("poem.txt","r")
all_contents=input_file.read()
print(all_contents)
input_file.close()
Athingofbeautyisajoyforever:
Itslovelinessincreases;itwillnever
Passintonothingness;...
JohnKeat
input_file=open("poem.txt","r")
some_contents=input_file.read(10)
print(some_contents)
Athingof
print(len(some_contents))
10
input_file.close()
CompSci101-PrinciplesofProgramming
21
CompSci101-PrinciplesofProgramming
22
Anoteabouttheread()funcLons
Thereadline()/readlines()methods
! NotethatthefilevariablereadsfromwhicheverposiLonin
thefileitiscurrentlypoinLngto,e.g.,
! Thereadline()methodreturnsthenextlineofthefile.This
methodreturnsastring.Thenewlinecharacteristhelast
characterofthestringreturned.
! Thereadlines()methodreturnsalistoftheremaininglines
ofthefile.Thismethodreturnsalistofstrings.Thenew
linecharacteristhelastcharacterofeachstringinthelist
(exceptforthelastelement).
input_file=open("poem.txt","r")
some_characters=input_file.read(10)
print(some_characters)
Athingof
print()
beautyisajoyforever:
Itslovelinessincreases;itwillnever
all_contents=input_file.read()
Passintonothingness;...
print(all_contents)
JohnKeat
input_file.close()
CompSci101-PrinciplesofProgramming
list_of_lines = input_file.readlines()!
23
Thereadline()andreadlines()methods-examples
! BoththefollowingsecLonsofcodeusethefilebelow:
input_file=open("RedHerring.txt","r")
one_line=input_file.readline()
ARedHerring:AdistracRonfromthemainissue.
print(one_line)
input_file=open("RedHerring.txt","r")
Aredherringhasastrongodour.
list_of_lines=input_file.readlines()
thesmelloftheherringandstart
print(list_of_lines[2])
6
print(list_of_lines[4])
print(len(list_of_lines) Notethatthestringreadfromthetextcontains
thenewlinecharacter.
next_line = input_file.readline()!
CompSci101-PrinciplesofProgramming
24
ShowthecontentsoftheOutBoard.txtfile
defmain():
input_file=open("AboveBoard.txt","r")
output_file=open("OutBoard.txt",'w')
line_list=input_file.readlines()
forlineinline_list:
ifline[0]=='p'orline[0]=='A':
output_file.write(line)
input_file.close()
output_file.close()
print()
main()!!
CompSci101-PrinciplesofProgramming
25
CompSci101-PrinciplesofProgramming
CompletethefuncLon
! Completetheget_percent_vowels()
funcLonwhichreturnsthe
percentageofle_ersinthetext
(roundedtoawholenumber)which
arevowels.Ignoreallspaces.
! Thecopy_file()funcLontakesthenamesofaninputfile
andanoutputfile,copiesdatafromtheinputfiletothe
outputfileandreturnsastringmadeupofthefirstandlast
charactersinthefile.
defget_percent_vowels(filename):
vowels="aeiouAEIOU"
def copy_file(filename_in, filename_out):
def main():
input_f = "FreeAdviceIn.txt"
output_f = "FreeAdviceOut.txt"
first_last_chars = copy_file(input_f, output_f)
print(first_last_chars)
F!
main()!!
defmain():
input_f="PoetryPrize.txt"
percent_vowels=get_percent_vowels(input_f)
print(str(percent_vowels)+"%arevowels")
31%arevowels
main()!!
CompSci101-PrinciplesofProgramming
27
Summary
! InaPythonprogram:
! a'datastream'canbecreatedbetweentheprogramandafile
! datacanbewri_entoafile
! datacanbereadfromafile
! afileshouldbeclosedoncetheprogramhasfinishedreadingor
wriLngtothefile
! InCompSci101wearedealingwithtextfilesonly.
! Thefilesystemisahierarchicalstructure
26
CompletethefuncLon
CompSci101-PrinciplesofProgramming
28
ExamplesofPythonfeaturesusedinthislecture
!def read_poem():!
! !input_file = open("poem.txt", "r")!
! !all_contents = input_file.read()!
! !input_file.close()!
! !print(all_contents)!
! !print()!
! !!
def write_to_file(filename, list1, list2):!
! !output_file = open(filename, "w")!
! !for i in range(len(list1)):!
! ! !output_file.write(str(list1[i]))!
! ! !output_file.write(": ")!
! ! !output_file.write(str(list2[i]) + "\n")!
!
! !output_file.close()!
!