On line 159, we define our csv_writer() function. Before writing our transaction data to a CSV file, we log our current execution phase and create a headers variable. This headers list represents the columns in our spreadsheet and will be the first row written to the file, as follows:
159 def csv_writer(data, output_dir):
160 """
161 The csv_writer function writes transaction data into a CSV file
162 :param data: The parsed transaction data in nested list
163 :param output_dir: The output directory to write the CSV
164 results
165 :return: Nothing
166 """
167 logging.info('Writing output to {}'.format(output_dir))
168 print('Writing output.')
169 headers = ['Index', 'Date', 'Transaction Hash',
170 'Inputs', 'Outputs', 'Values', 'Total']
As with any user-supplied data, we must account for the possibility that the supplied data could be incorrect or generate an exception. For example, the user could specify a non-existent directory in the output path argument. On lines 173 and 175, we open the csvfile in the appropriate manner, depending on the version of Python being used, and write our CSV data under one try and except clause. If there's an issue with the user-supplied output, we'll receive an IOError exception.
We create our writer object on line 177 and write our headers, before iterating through our transactions list. Every transaction within the transactions list is written on its own row. Finally, on lines 181 and 182, we flush and close the CSV file:
171 try:
172 if sys.version_info[0] == 2:
173 csvfile = open(output_dir, 'wb')
174 else:
175 csvfile = open(output_dir, 'w', newline='')
176 with csvfile:
177 writer = csv.writer(csvfile)
178 writer.writerow(headers)
179 for transaction in data:
180 writer.writerow(transaction)
181 csvfile.flush()
182 csvfile.close()
If IOError is generated, we write the error message and contextual information to the log before exiting with an error (any nonzero exit). If there are no errors generated, we log the completion of the script and exit without errors (also known as a zero exit), as seen on line 191 through 193:
183 except IOError as e:
184 logging.error("""Error writing output to {}.
185 \nGenerated message: {}.""".format(e.filename,
186 e.strerror))
187 print("""Error writing to CSV file.
188 Please check output argument {}""".format(e.filename))
189 logging.info('Program exiting.')
190 sys.exit(1)
191 logging.info('Program exiting.')
192 print('Program exiting.')
193 sys.exit(0)