Created
January 11, 2012 07:15
-
-
Save sonkm3/1593511 to your computer and use it in GitHub Desktop.
python csvを文字列で取得したかった
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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