Skip to content

Instantly share code, notes, and snippets.

@casouri
Created September 30, 2017 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save casouri/52a45a6069c828f93ffe93a4fc6e2e3f to your computer and use it in GitHub Desktop.
Save casouri/52a45a6069c828f93ffe93a4fc6e2e3f to your computer and use it in GitHub Desktop.
create csv budget file from a list of records
# -*- coding: utf-8 -*-
'''
copy data into datain file under root folder
every record are separate by newling
first line is title
a csv file will be ceated
'''
import re
from csv import DictWriter
# read budget recording
with open('datain', 'r') as f:
data = f.read()
# split into list by newline
listOfRecords = data.split('\n')
title = listOfRecords.pop(0)
# output lists
outputRecordList = []
errorList = []
# separate price and name, put into dict
for record in listOfRecords:
try:
cost = re.search('[0-9]*.*[0-9]+', record).group(0)
item = record.replace(cost, '').lstrip().rstrip()
outputRecordList.append({'item': item, 'cost': cost})
print('item: {0:8} cost: {1:8}'.format(item, cost))
except Exception as e:
errorList.append((record, e))
# write to a csv file
with open('{}.csv'.format(title), 'w') as outfile:
writer = DictWriter(outfile, ('item', 'cost'))
writer.writeheader()
writer.writerows(outputRecordList)
# print errors
if errorList is not None:
for errorRecord in errorList:
print(errorRecord[0], errorRecord[1])
else:
print('no error')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment