python - 如何在 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")
解决方案
您应该以“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
试试这个可能会有所帮助
推荐阅读
- python-3.x - 如何在 python scrapy 中修复蜘蛛内部的回调?
- amazon-web-services - 使用 CLI 将对象与过期和缓存控制标头同步到 S3?
- python-3.x - 套接字服务器 - readlines() 函数导致我的程序停止/卡住
- javascript - 如何使用 d3 使用 javascript 可视化本地 csv 文件?
- php - Codeigniter 应用程序中大量 mpdf 事务的服务器超时
- java - 使用名称创建 bean 时出错:注入自动装配的依赖项失败,无法解析占位符
- apache - 在 solr 服务器重新启动时丢失 solr 数据
- node.js - 使用 Mocha 对在 AMQP 消息接收事件时应触发的回调进行集成测试
- python - 使用“SearchFilter”时,尝试搜索时出现错误
- visual-c++ - 使用构造函数在类中初始化字符串