Skip to content

Instantly share code, notes, and snippets.

@sonkm3
Created January 11, 2012 07:15
Show Gist options
  • Save sonkm3/1593511 to your computer and use it in GitHub Desktop.
Save sonkm3/1593511 to your computer and use it in GitHub Desktop.
python csvを文字列で取得したかった
# -*- coding: utf-8 -*-
import csv
import StringIO
s = StringIO.StringIO()
csv_writer = csv.writer(s)
list = [
{'name': 'item1', 'value': 'foo string'},
{'name': 'item2', 'value': 'bar "quoted" string'},
{'name': 'item3', 'value': u'unicode文字列'},
]
for item in list:
# csv用のタプルを作る
_item = (
'string',
item['name'],
item['value'],
)
# unicode文字列はutf8に変換する
item_out = [ _str.encode('utf8') for _str in _item]
csv_writer.writerow(item_out)
csv = s.getvalue()
s.close()
print csv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment