To answer your questions…
- Your approach is fine.
- Move your hundreds of lines into a function, then break down that function into reasonable-sized chunks. If it's still huge and ugly, then pose that as another code review question.
- If an error other an
IOErroroccurred, then the error would not get caught. However, when thewithblock is exited for any reason,input_fileandoutput_filewill get properly closed.
In addition to what @JimDennis said, I would like to point out that it it customary to print error messages to sys.stderr, and exit with a non-zero status when an error occurs.
def process(csv_reader, csv_writer):
for row in csv_reader:
# many lines of code...
def main(input_filename, output_filename):
try:
with open(input_filename, 'rb') as in_csv, open(output_filename , 'wb') as out_csv:
writer = csv.writer(out_csv, delimiter='\t')
reader = csv.reader(in_csv, delimiter='\t')
process(reader, writer)
except IOError as e:
print >> sys.stderr, "Error: cannot open file"
if e.errno == errno.EACCES:
print >> sys.stderr, "\tPermission denied."
print >> sys.stderr, "\tError message: {0}".format(e)
sys.exit(1)
# Not a permission error.
print >> sys.stderr, "\tError message: {0}".format(e)
sys.exit(1)
except Exception as other_exception:
print >> sys.stderr, "Error: " + str(other_exception)
sys.exit(2)
if __name__ == '__main__':
main('in_file.csv', 'out_file.csv')