【发布时间】:2011-06-23 07:07:55
【问题描述】:
下午,
我在使用 SQLite 到 CSV python 脚本时遇到了一些问题。我搜索过高,也搜索过低,但没有一个对我有用,或者我的语法有问题。
我想替换 SQLite 数据库中不属于 ASCII 表(大于 128)的字符。
这是我一直在使用的脚本:
#!/opt/local/bin/python
import sqlite3
import csv, codecs, cStringIO
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([unicode(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)
conn = sqlite3.connect('test.db')
c = conn.cursor()
# Select whichever rows you want in whatever order you like
c.execute('select ROWID, Name, Type, PID from PID')
writer = UnicodeWriter(open("ProductListing.csv", "wb"))
# Make sure the list of column headers you pass in are in the same order as your SELECT
writer.writerow(["ROWID", "Product Name", "Product Type", "PID", ])
writer.writerows(c)
我已尝试添加此处所示的“替换”,但出现了相同的错误。 Python: Convert Unicode to ASCII without errors for CSV file
错误是 UnicodeDecodeError。
Traceback (most recent call last):
File "SQLite2CSV1.py", line 53, in <module>
writer.writerows(c)
File "SQLite2CSV1.py", line 32, in writerows
self.writerow(row)
File "SQLite2CSV1.py", line 19, in writerow
self.writer.writerow([unicode(s).encode("utf-8") for s in row])
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 65: ordinal not in range(128)
显然,我希望代码足够健壮,如果遇到超出这些范围的字符,它会用诸如“?”之类的字符替换它。 (\x3f)。
有没有办法在 UnicodeWriter 类中做到这一点?还有一种方法可以使代码变得健壮,不会产生这些错误。
非常感谢您的帮助。
【问题讨论】: