python - 无法在打开 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>
我很确定这只是我想念的一件愚蠢的事情,但我做不到。感谢您的关注!
解决方案
推荐阅读
- c# - Visual Studio 扩展:如何禁用本机命令?
- c++ - 如何在directx11着色器中使用swizzle .rrrg
- r - 根据模式从字符串中提取项目
- ios - 有什么方法可以在 iOS 中归档发布版本之前自动运行我的所有单元测试
- java - 如何将 Java Map 中的属性自动映射到 POJO 类属性
- dart - Flutter:从另一个 Dart 文件中获取 AlertDialog
- javascript - 在浏览器中检测实时音频输入的音高
- javascript - 使用Javascript从右到左插入排序
- asp.net - 在代码中设置 Bugsnag 配置选项
- python - 如何从 CSV 中正确提取值?- Python