You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3实现用户输入书籍信息追加至CSV指定列的问题求助

解决CSV追加书籍信息的问题

看起来你在实现书籍收藏程序时,卡在了将新书信息正确追加到CSV文件的环节,我帮你梳理下代码里的问题并给出修正方案:

代码里的几个关键问题

  • 文件打开模式错误:Python 3中使用csv.writer时,用二进制模式'ab'会导致换行符处理异常,应该用文本追加模式'a',同时指定newline=''来避免写入后出现多余空行。
  • 方法参数缺失:你的add_book方法没有接收用户输入的书名和作者,导致方法内部无法访问nbt和author变量。
  • 错误的列名获取方式:csv.writer是用于写入数据的对象,不能从中读取列名。你只需要确保写入的顺序和CSV的表头(title,author)对应即可。
  • 语法错误:writer.writerows(zip(nbt, author)这行缺少闭合括号,而且writerows是写入多行,这里我们只需要写入一行数据,用writerow更合适。

修正后的完整代码

import csv
import random

class Book(object):
    def __init__(self):
        self.csvfile = r'/Users/anthonymandelli/Repos/nextbook/Books.csv'
        # 可选:如果CSV文件可能为空,初始化时检查并写入表头
        self._ensure_header()

    def _ensure_header(self):
        """确保CSV文件存在正确的表头"""
        try:
            with open(self.csvfile, 'r') as f:
                # 读取第一行判断是否有表头
                header = f.readline().strip().lower()
                if header != 'title,author':
                    # 如果表头不对,重新写入表头和原有内容
                    with open(self.csvfile, 'w', newline='') as fw:
                        writer = csv.writer(fw)
                        writer.writerow(['title', 'author'])
                        # 把原有内容写回去
                        f.seek(0)
                        for line in f:
                            fw.write(line)
        except FileNotFoundError:
            # 文件不存在时创建并写入表头
            with open(self.csvfile, 'w', newline='') as f:
                writer = csv.writer(f)
                writer.writerow(['title', 'author'])

    def add_book(self, title, author):
        # 用文本追加模式打开,指定newline=''避免多余空行
        with open(self.csvfile, 'a', newline='') as library:
            writer = csv.writer(library, delimiter=',')
            # 将书名和作者作为一行写入,顺序对应表头的title和author
            writer.writerow([title, author])
            return f"Added {title} by {author}"

NewBook = Book ()
if __name__ == '__main__':
    while True:
        print("\nAdd a new book to the library:")
        print()
        book_title = input("Title: ").title()
        book_author = input("Author: ").title()
        print()
        print(NewBook.add_book(book_title, book_author))
        # 增加选项让用户选择是否继续添加
        continue_add = input("Add another book? (y/n): ").lower()
        if continue_add != 'y':
            break

关键修改说明

  1. 新增_ensure_header方法:用来确保CSV文件始终有正确的表头title,author,如果文件不存在会自动创建并写入表头;如果表头缺失或不正确,会修复表头同时保留原有数据。
  2. 修改add_book方法:新增title和author参数接收用户输入的信息;使用正确的文件打开模式'a'和newline='';用writerow写入单行数据,顺序和表头严格对应。
  3. 主程序调整:把用户输入的内容赋值给普通变量(不再用列表),传递给add_book方法,同时增加了是否继续添加的选项,提升用户体验。

这样修改后,用户输入的书名和作者就会被正确追加到CSV文件的新行中,分别对应title列和author列啦。

内容的提问来源于stack exchange,提问作者Mandelliant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:16:38