为了账号安全,请及时绑定邮箱和手机立即绑定

在python中导出utf-8 csv文件

在python中导出utf-8 csv文件

Qyouu 2021-03-29 17:04:08
在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)看起来每一行都包含一些整数和日期时间的东西。有解决这个问题的想法吗?非常感谢!
查看完整描述

1 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

您可能需要先执行以下操作,然后再执行以下操作writer.writerows

rows = [[unicode(x) for x in row] for row in rows]

或者,我的猜测是试图写数据库行ID的麻烦。因此,您也可以尝试将其切成薄片:

rows = [row[1:] for row in rows]


查看完整回答
反对 回复 2021-04-02
  • 1 回答
  • 0 关注
  • 325 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信