在python中导出utf-8 csv文件时遇到错误。错误说
AttributeError: 'int' object has no attribute 'encode'
首先,我使用pyodbc连接Microsoft Access数据库并在那里获取数据。
MDB = "E:/Research/2000-01.mdb"; DRV = '{Microsoft Access Driver (*.mdb)}'; PWD = 'pw'
con = pyodbc.connect('DRIVER={};DBQ={};PWD={}'.format(DRV,MDB,PWD))
cur = con.cursor()
SQL = 'SELECT * FROM 200001;'
rows = cur.execute(SQL).fetchall()
cur.close()
con.close()
然后使用该类,
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
我开始写utf-8 csv文件
with open("E:/Research/200001.txt", 'wb') as f:
writer = UnicodeWriter(f)
writer.writerows(rows)
看起来每一行都包含一些整数和日期时间的东西。有解决这个问题的想法吗?非常感谢!
慕哥6287543
相关分类