我有一个问题,我绝对不知道为什么会这样。我尝试了一百万次,但无济于事。这只是一个简单的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>
我很确定这只是我所缺少的愚蠢的东西,但我做不到。谢谢您的关注!
我有一个问题,我绝对不知道为什么会这样。我尝试了一百万次,但无济于事。这只是一个简单的OOP任务,但是我是Python的新手,而且很棘手。我有这个...
我建议您检查并使用csv库,它使使用和管理csv文件变得非常容易。 Python CSV documentation