首页 > 解决方案 > 如何在 Python 中编辑 CSV 中的值

问题描述

我开始学习 python,我有这个项目,我有一个菜单,可以添加、列出或更新 csv 中书籍的值。标题是“BookName”、“AuthorName”、“SharedWith”、“IsRead”,我正在尝试更改用户添加的给定书籍的“IsRead”行。我的问题是,每当我尝试编辑包含该书的行时,我最终都会删除所有其他行。我要做的就是更新 csv 中某一行的值。这是我写的函数。

def updateBook():
book_name = input("Enter book name: ")
import csv
rows_list = []
with open('booksDB.csv', mode='r') as file:
    rows = list(csv.DictReader(file, fieldnames=("BookName", "AuthorName", "SharedWith", "IsRead")))
    for row in rows:
        rows_list.append(row["BookName"]) # we store every book name in a list
    if book_name not in rows_list: # we search the book the user typed in our list
        add_new_book = input(f' The {book_name} book does not exits. Would you like to add it? (Y/N)? ')
        if add_new_book.upper() == "N":
            return
        else:
            addBook()
            return
    else:
        book_read = input("Is the book read? (Y/N)? ")
        if book_read.upper() == 'Y':
            book_read = True
        else:
            book_read = False
        rows = []
with open('booksDB.csv', mode='r') as file:
    rows = list(csv.DictReader(file, fieldnames=("BookName", "AuthorName", "SharedWith", "IsRead")))
    for row in rows:
        if row["BookName"] == book_name:
            row["IsRead"] = book_read
            break
with open('booksDB.csv',mode='r+') as file:  # WIP, here I can't make the csv keep all books in the list when editing a certain one
    csv_writer = csv.DictWriter(file, fieldnames=[
        "BookName", "AuthorName", "SharedWith", "IsRead"
    ])
    if row["IsRead"] == book_read:
        csv_writer.writerow({"BookName": row.get("BookName"),
                             "AuthorName": row.get("AuthorName"),
                             "SharedWith": row.get("SharedWith"),
                             "IsRead": book_read})
    print("Book was updated successfully")

标签: pythoncsv

解决方案


您应该以“w”模式而不是“r”模式打开 CSV 文件的第一件事

在我查看了您的代码之后,您不尊重您的功能的缩进尝试先修复它

您是否尝试过先提供输入

roww = input("Enter The Name Of The Row Here : ")

和使用后:

for row in rows:
    if row["BookName"] == book_name:
        row[rf"{roww}"] = book_read
        break

试试这个可能会有所帮助


推荐阅读