0

由于我尝试了不同代码和 csv.reader 方言的所有可能变体,因此我的 csv 文件总是存在双引号行的问题。我找不到原因。如果行只有标准逗号和一个带有空格的字符串,它可以工作,但如果双引号字符串中有逗号或单引号,它表示该行有一个项目,而不是它应该是的。每行的预期列表项:isbn、标题、作者和年份。我已经阅读了所有 github 解决方案,所有代码几乎相同,它们都使用简单csv.reader(f),没有任何特殊方言,但我的代码不起作用。我在什么时候错了?

import csv
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine("postgresql://goga:0000@localhost/mydb")
db = scoped_session(sessionmaker(bind=engine))

def main():
    db.execute("CREATE TABLE books (id SERIAL PRIMARY KEY, isbn VARCHAR NOT NULL, title VARCHAR NOT NULL, author VARCHAR NOT NULL, year VARCHAR NOT NULL)")
    f = open("books.csv")
    reader = csv.reader(f)
    next(reader, None)

    for isbn, title, author, year in reader:
        db.execute("INSERT INTO books (isbn, title, author, year) VALUES 
(:isbn,:title,:author,:year)",
               {"isbn": isbn, "title": title, "author": author, "year": year})
        print(f"Added book {isbn} : {title} : {author} : {year}.")

    db.commit()


if __name__ == "__main__":
    main()

错误部分:

Added book 0006161413 : Ice Station Zebra : Alistair MacLean : 1963.
Added book 0385491069 : The Edible Woman : Margaret Atwood : 1969.
Added book 0451208188 : The English Assassin : Daniel Silva : 2002.
Added book 0312942303 : Born of the Night : Sherrilyn Kenyon : 1996.
Added book 0385366434 : Two Ravens and One Crow : Kevin Hearne : 2012.
Added book 0345438310 : Nicholas and Alexandra : Robert K. Massie : 1967.
Added book 0060652381 : A Grief Observed : C.S. Lewis : 1961.
Traceback (most recent call last):
  File "lucky.py", line 33, in <module>
    main()
  File "lucky.py", line 24, in main
    for isbn, title, author, year in reader:
ValueError: not enough values to unpack (expected 4, got 1)

C:\Users\user\PycharmProjects\whichbook>

books.csv 文件链接

CSV 样本:

312349513,Fearless Fourteen,Janet Evanovich,2008
1561797464,A Christmas Carol,Charles Dickens,1843
767915593,Straight Talking,Jane Green,1997
1400078776,Never Let Me Go,Kazuo Ishiguro,2005
6161413,Ice Station Zebra,Alistair MacLean,1963
385491069,The Edible Woman,Margaret Atwood,1969
451208188,The English Assassin,Daniel Silva,2002
312942303,Born of the Night,Sherrilyn Kenyon,1996
385366434,Two Ravens and One Crow,Kevin Hearne,2012
345438310,Nicholas and Alexandra,Robert K. Massie,1967
60652381,A Grief Observed,C.S. Lewis,1961
140690483X,"Right Ho, Jeeves",P.G. Wodehouse,1934
743482883,Mr. Perfect,Linda Howard,2000
4

0 回答 0