Python 字符串中有''时sqlite无法正确写入

Python Sqlite can't write correctly when there is "’" in a string

我正在尝试使用 python CSV 模块将一些新闻标题写入 CSV,但似乎当标题中有撇号时,例如 'What’s So Great About Snapchat Anyway?',则会显示编码错误向上。

错误如下:

代码:

对这个错误有什么想法或建议吗?

Python2.7 csv 模块本身无法处理 unicode。但是 docs 在 class UnicodeWriter 中有一个如何做到这一点的例子。您也可以尝试 python3 因为那里的 csv 模块将本地处理 unicode。

此片段已从我链接的文档中无耻地撕下

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)

那你就可以称之为做

writer = UnicodeWriter(open("foo", "w"))
writer.writerow(['1', 'bar'])