process_file()
opens a file and reads it# ################################ Process file: LBYL version ################################
import os
p = '/path/to/datafile.dat'
if os.path.exists(p):
process_file(p)
else:
print(f'No such file as {p}')
### ISSUES
# what if file's contents aren't valid?
# what if path leads to directory?
# BONUS: there is race condition where file could be deleted AFTER check but BEFORE processing
# ################################ Process file: EAFP version ################################
p = '/path/to/datafile.dat'
try:
process_file(f)
except OSError as e:
print(f'Error: {e}')
As a practice when using try/except
, you should specify the type of exception being handled
try...except
except
block is passed argument of exception type(s)
except
blocks per try
blocktuple
as argument, which allows for passing multiple types of exceptions