So I have a problem with project1, specifically in import.py. In the csv provided with the books information, some of them have a comma inside the title, and this is causing the following error when I execute the file:

Added book with title: Krondor: The Betrayal, author: Raymond E. Feist, ISBN: 0380795272 and year: 1998.
Added book with title: The Dark Is Rising, author: Susan Cooper, ISBN: 1416949658 and year: 1973.
Added book with title: The Black Unicorn , author: Terry Brooks, ISBN: 1857231082 and year: 1987.
Traceback (most recent call last):
  File "import.py", line 19, in <module>
  File "import.py", line 13, in main
    for isbn, title, author, year in reader:
ValueError: not enough values to unpack (expected 4, got 1)

If I remove the comma of the title of the book causing this problem, the problem seems to dissapear.

This is my code for importing the books:

f = open("books.csv")
    reader = csv.reader(f)
    for isbn, title, author, year in reader:
        db.execute("INSERT INTO books (id, title, year, author) VALUES (:id, :title, :year, :author)",{"id": isbn, "title": title, "year": year, "author":author})
        print (f"Added book with title: {title}, author: {author}, ISBN: {isbn} and year: {year}.")

How could I avoid this problem?


If a comma appears, it defines a separation between values. However, if a string is contained in quotes, any commas inside the string is treated as part of the string and not as a delimiter. Try putting double quotes around the title before putting it in the :title variable.

  • Hi, I've tried putting the double quotes, but that's what I get :( File "import.py", line 14 db.execute("INSERT INTO books (isbn, title, year, author) VALUES (:isbn, ":title", :year, :author)", ^ SyntaxError: invalid syntax – Eric Koenig Apr 6 '20 at 19:19
  • THat's not what I meant. think like this :title = "something,more something" The double quotes need to be inside the var, with the text of the title. – Cliff B Apr 6 '20 at 19:35
  • Oh, I understand. The thing is that the titles are already inside double quotes, that's why I don't understand why I get that error. – Eric Koenig Apr 6 '20 at 19:43
  • Okay, I think I just found the problem. Thanks! – Eric Koenig Apr 6 '20 at 19:46
  • Well? Are you going to share???? ;-) You are allowed to answer your own question!!! – Cliff B Apr 6 '20 at 19:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .