Skip to main content
2 of 2
All errors go to stderr. Don't speculate on uncertain cause of error.
200_success
  • 145.6k
  • 22
  • 191
  • 481

To answer your questions…

  1. Your approach is fine.
  2. 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.
  3. If an error other an IOError occurred, then the error would not get caught. However, when the with block is exited for any reason, input_file and output_file will 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')
200_success
  • 145.6k
  • 22
  • 191
  • 481