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!

Mandelliant
  • 36
  • 1
  • 6

0 Answers0