猿问

在python中导出utf-8 csv文件

在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)


看起来每一行都包含一些整数和日期时间的东西。有解决这个问题的想法吗?非常感谢!


Qyouu
浏览 326回答 1
1回答

慕哥6287543

您可能需要先执行以下操作,然后再执行以下操作writer.writerows:rows = [[unicode(x) for x in row] for row in rows]或者,我的猜测是试图写数据库行ID的麻烦。因此,您也可以尝试将其切成薄片:rows = [row[1:] for row in rows]
随时随地看视频慕课网APP

相关分类

Python
我要回答