Skip to content

Instantly share code, notes, and snippets.

@allieus
Created August 20, 2012 04:13
Show Gist options
  • Save allieus/3400746 to your computer and use it in GitHub Desktop.
Save allieus/3400746 to your computer and use it in GitHub Desktop.
Python Generator 을 이용해서 CSV, XSLX 생성해보기
from openpyxl import Workbook
import random
def get_row_data():
for i in xrange(1000):
rand_num = random.randint(0, 100)
yield (i, (i, rand_num, i + rand_num))
def write_to_csv(filepath):
with open(filepath, 'wt') as f:
for (row_idx, data) in get_row_data():
print row_idx
a, b, c = data
print >>f, (u'%s,%s,%s' % (a, b, c)).encode('utf-8')
print 'save to', filepath
def write_to_xlsx(filepath):
wb = Workbook()
worksheet = wb.create_sheet(0)
for (row_idx, data) in get_row_data():
print row_idx
a, b, c = data
worksheet.cell(row=row_idx, column=0).value = a
worksheet.cell(row=row_idx, column=1).value = b
worksheet.cell(row=row_idx, column=2).value = c
print 'save to', filepath
wb.save(filepath)
if __name__ == '__main__':
write_to_csv('data.csv')
# write_to_xlsx('data.xlsx')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment