1

I'm working on a program that allows a user to add new books to their collection and then generate a random suggestion. Right now I'm stuck trying to add the new books to the csv file. I've looked at other answers on writing and appending to csv's, but they all seemed to want to just produce output organized by columns. My goal is to let a user input a title and an author, then have those inputs added into a new row within the csv file.

Here's where I am:

import csv
import random

class Book(object):

    def __init__(self):
        self.csvfile =
        r'/Users/anthonymandelli/Repos/nextbook/Books.csv'

    def add_book(self):
        with open(self.csvfile, 'ab') as library:

            writer = csv.writer(library, delimiter = ',')

            tcolumn = [column for column in writer if column == 'title'.lower()]

            acolumn = [column for column in writer if column == 'author'.lower()]

            writer.writerows(zip(nbt, author)

            return "Added {}".format(newbook)


NewBook = Book ()

if __name__ == '__main__':
    while True:
        print("\nAdd a new book to the library:")
        print()

        nbt = [input("Title: ").title()]
        author = [input("Author: ").title()]
        newbook = '{} by {}'.format(nbt, author)

        print()
        print(NewBook.add_book())
        break

Ideally, a new row will be created with nbt in the title column and author in the author column. This answer seems to be closest to what I want, but I'm missing something and can't connect the dots between those answers and my problem. This is only part of the code, what I assume to be the relevant part, but you can see the whole program here.

Any tips would be greatly appreciated!

2
  • a ' at the end of your filename r'/Users/anthonymandelli/Repos/nextbook/Books.csv is breaking the syntax coloration making your code more dificult to read Commented Jan 25, 2018 at 13:49
  • @SimonC. thanks for pointing that out Commented Jan 25, 2018 at 13:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.