首页 > 解决方案 > 无法在打开 CSV 文件时解码字符

问题描述

我有一个问题,我完全不知道为什么会这样。我尝试了一百万件事,但无济于事。这只是一个简单的 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>

我很确定这只是我想念的一件愚蠢的事情,但我做不到。感谢您的关注!

标签: pythonfilecsvdecode

解决方案


推荐阅读