简而言之,我的问题是我的脚本无法将完整的 unicode 字符串(从数据库中检索)写入 csv,而只是将每个字符串的第一个字符写入文件。例如:
U,1423.0,831,1,139
输出应该在哪里:
University of Washington Students,1423.0,831,1,139
一些背景知识:我正在使用 pyodbc 连接到 MSSQL 数据库。我为 unicode 设置了我的 odbc 配置文件,并按如下方式连接到数据库:
p.connect("DSN=myserver;UID=username;PWD=password;DATABASE=mydb;CHARSET=utf-8")
我可以毫无问题地获取数据,但是当我尝试将查询结果保存到 csv 文件时出现问题。我试过使用 csv.writer,UnicodeWriter官方文档中的解决方案,最近,unicodecsv我在github上找到的模块。每种方法产生相同的结果。
奇怪的是我可以毫无问题地在 python 控制台中打印字符串。然而,如果我采用相同的字符串并将其写入 csv,问题就会出现。请参阅下面我的测试代码和结果:
突出问题的代码:
print "'Raw' string from database:"
print "\tencoding:\t" + whatisthis(report.data[1][0])
print "\tprint string:\t" + report.data[1][0]
print "\tstring len:\t" + str(len(report.data[1][0]))
f = StringIO()
w = unicodecsv.writer(f, encoding='utf-8')
w.writerows(report.data)
f.seek(0)
r = unicodecsv.reader(f)
row = r.next()
row = r.next()
print "Write/Read from csv file:"
print "\tencoding:\t" + whatisthis(row[0])
print "\tprint string:\t" + row[0]
print "\tstring len:\t" + str(len(row[0]))
测试输出:
'Raw' string from database:
encoding: unicode string
print string: University of Washington Students
string len: 66
Write/Read from csv file:
encoding: unicode string
print string: U
string len: 1
此问题可能是什么原因造成的,我该如何解决?谢谢!
编辑:whatisthis 函数只是检查字符串格式,取自 this post
def whatisthis(s):
if isinstance(s, str):
print "ordinary string"
elif isinstance(s, unicode):
print "unicode string"
else:
print "not a string"
请您参考如下方法:
import StringIO as sio
import unicodecsv as ucsv
class Report(object):
def __init__(self, data):
self.data = data
report = Report(
[
["University of Washington Students", 1, 2, 3],
["UCLA", 5, 6, 7]
]
)
print report.data
print report.data[0][0]
print "*" * 20
f = sio.StringIO()
writer = ucsv.writer(f, encoding='utf-8')
writer.writerows(report.data)
print f.getvalue()
print "-" * 20
f.seek(0)
reader = ucsv.reader(f)
row = reader.next()
print row
print row[0]
--output:--
[['University of Washington Students', 1, 2, 3], ['UCLA', 5, 6, 7]]
University of Washington Students
********************
University of Washington Students,1,2,3
UCLA,5,6,7
--------------------
[u'University of Washington Students', u'1', u'2', u'3']
University of Washington Students
谁知道你的 whatisthis() 函数在搞什么鬼。
