在打开CSV文件时无法解码字符。

问题描述 投票:0回答:1

我有一个问题,我完全不知道为什么会发生这种情况。我尝试了无数种方法,但都无济于事。这只是一个简单的OOP赋值,但我是Python新手,我被卡住了。

我有一个目录树。

Assignment
|
|___project
    |
    |__src
       |   __init__.py
       |   book.py
       |   books.csv
       |   database.py
       |   main.py
       |
       |__.vscode
       |
       |__ __pycache__

所以在database.py中 我想打开books.csv文件 把它的内容包含在一个列表中 就像这样:

class Database(object):

    db = []

    with open('books.csv', newline='') as f:
        reader = csv.reader(f)
        db = list(reader)

这些是csv文件的内容。

The Lord of the Rings,J. R. R. Tolkien,0395595118
The Alchemist (O Alquimista),Paulo Coelho,9780061122415
The Little Prince (Le Petit Prince),Antoine de Saint-Exupéry,0156012197
Harry Potter and the Philosopher's Stone,J. K. Rowling,9780747532743
The Master and Margarita (Мастер и Маргарита),Mikhail Bulgakov,0143108271
Alice's Adventures in Wonderland,Lewis Carroll,0744561248
The Hobbit,J. R. R. Tolkien,054792822X
And Then There Were None,Agatha Christie,0062073486
Dream of the Red Chamber (紅樓夢),Cao Xueqin,0146001761

我收到了这个错误。

File "c:\Users\castr\Desktop\Assignment\project\src\database.py", line 4, in <module>
    class Database(object):
  File "c:\Users\castr\Desktop\Assignment\project\src\database.py", line 10, in Database
    db = list(reader)
  File "C:\Users\castr\AppData\Local\Programs\Python\Python38-32\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 279: character maps to <undefined>

我很确定这只是我漏掉的一个愚蠢的东西,但我做不到。谢谢您的关注!

python file csv oop decode
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.