Read line and back to the start location of the file
123
data=open('sketch.txt')print(data.readline(),end='')data.seek(0)# “rewind” a file to the beginning
Process every line of a file
12
foreachLineindata:print(eachLine,end='')
Using split() method to process each line to extract part of the line
12345678910111213141516171819
importosifos.path.exists('sketch.txt'):data=open('sketch.txt')foreachLineindata:# only process the line that contains ':'ifnoteachLine.find(':')==-1:# optional arg is set to 1, line of data is only broken into 2 pieces(role,line_spoken)=eachLine.split(':',1)line_spoken=line_spoken.strip()print(role,end='')print(' said: ',end='')print(line_spoken,end='')data.close()else:print('The data file is missing!')
Handle Exceptions: try/except Machanism
Python try to run code first, then deal with runtime errors (exceptions) as they happen
Python catch exceptions as they occur, gives you a chance to possibly recover from the error and, critically, not crash
12345678910111213141516171819
try:data=open('sketch.txt')foreachLineindata:try:(role,spoken)=eachLine.split(':',1)line_spoken=line_spoken.strip()print(role,end='')print(' said: ',end='')print(spoken,end='')# for handling the case there is no ':' in a lineexceptValueError:passdata.close()exceptIOError:print('The data file is missing!')
Extend try/except with finally
No matter what errors occur, code in the finally suite is always run
man=[]other=[]try:data=open('sketch.txt')foreachLineindata:try:(role,spoken)=eachLine.split(':',1)spoken=spoken.strip()ifrole=='Man':man.append(spoken)elifrole=='Other Man':other.append(spoken)exceptValueError:passdata.close()exceptIOError:print('The data file is missing!')try:man_file=open('man_data.txt','w')other_file=open('other_data.txt','w')print(man,file=man_file)print(other,file=other_file)exceptIOErroraserr:print('File Error: '+str(err))finally:if'man_file'inlocals():man_file.close()if'other_file'inlocals():other_file.close()
Knowing the detailed error imformation
Python creates an exception object that is passed as an argument to the except suite
123456789101112
try:data=open('missingFile.txt')print(data.readline(),file=data)# the error imformation is named as 'err'exceptIOErroraserr:print('File error: '+str(err))finally:if'data'inlocals():data.close()# output:Fileerror:[Errno2]Nosuchfileordirectory:'missingFile.txt'
Use with to reduce the amount of code
The following code is identical to the former as a short version
importnesterman=[]other=[]try:data=open('sketch.txt')foreachLineindata:try:(role,line_spoken)=eachLine.split(':',1)line_spoken=line_spoken.strip()ifrole=='Man':man.append(line_spoken)elifrole=='Other Man':other.append(line_spoken)exceptValueError:passdata.close()exceptIOError:print('The data file is missing!')try:withopen('man_data.txt','w')asman_file,open('other_data.txt','w')asother_file:# format the output filesnester.print_item(man,fh=man_file)nester.print_item(other,fh=other_file)exceptIOErroraserr:print('File error: '+str(err))
Pickle the data
Store data using pickle.dump()
123456789101112131415161718192021
importpickleman=[]other=[]try:...exceptIOError:...try:# 'wb' indicate the access mode to be "writeable, binary"withopen('man_data.txt','wb')asman_file,open('other_data.txt','wb')asother_file:# store datapickle.dump(man,man_file)pickle.dump(other,other_file)exceptIOErroraserr:print('File error: '+str(err))# handle pickle exceptionsexceptpickle.PickleErrorasperr:print('Pickling error: '+str(perr))