簡體   English   中英

UnicodeDecodeError:寫入文件時

[英]UnicodeDecodeError: while writing into a file

寫入文件時出現此錯誤。 我該如何處理。

Traceback (most recent call last):
  File "C:\Python27\AureusBAXProjectFB.py", line 278, in <module>
    rows = [[unicode(x) for x in row] for row in outlist]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128)
>>> 

寫入文件的代碼

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)

with open('C:/Users/Desktop/fboutput.csv', 'wb') as f:
    writer = UnicodeWriter(f)
    rows = [[unicode(x) for x in row] for row in outlist]
    writer.writerows(rows)

我正在使用BeautifulSoup解析html數據,多數民眾贊成在正常工作。 僅在寫入文件時出現錯誤。

unicode()構造函數定義為unicode(string[, encoding, errors]) ,編碼默認為ascii。 如果多字節字符串在列表中,則應指定utf-8這樣的unicode編碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM