在Python3中定义用户输入值并附加到特定的CSV列

2024-09-29 01:21:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个程序,允许用户将新书添加到收藏中,然后生成一个随机建议。现在我被困在尝试添加到csv文件的新书。我看过其他关于编写和附加到csv的答案,但它们似乎都只想产生按列组织的输出。我的目标是让用户输入标题和作者,然后将这些输入添加到csv文件的新行中。你知道吗

我在这里:

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

理想情况下,将创建一个新行,标题列中有nbt,作者列中有authorThis answer似乎最接近我想要的,但我遗漏了一些东西,无法将这些答案和我的问题联系起来。这只是代码的一部分,我假设是相关的部分,但是您可以看到整个程序here。你知道吗

任何提示将不胜感激!你知道吗


Tags: 文件csv用户self程序iftitlelibrary