【问题标题】:Changing existing CSV file depending on user input根据用户输入更改现有 CSV 文件
【发布时间】:2018-03-18 16:54:46
【问题描述】:

我会尽量保持简短,因为我试图找到答案但我找不到。我正在尝试创建一个简单的直到系统。我正在使用 CSV 文件来存储产品的描述、价格和库存。如果用户以经理身份登录,他们将能够更改特定产品的库存。我觉得很难理解如何更换新库存。我忘了提到我使用列表来存储每个类别 假设我有以下文件

apples,1,11
grape,1.2,1
chocolate,0.75,15
bananas,1.35,27

以及创建列表的以下代码:

Products = []
Prices = []
Prices= []
import csv
with open('listlist.csv') as csvfile:
    readCSV = csv.reader(csvfile,delimiter=',')
    for row in readCSV:
        print(row)
        item = row[0]
        price = row[1]
        stock = row[2]
        Products.append(item)
        Prices.append(price)
        Stock.append(int(stock))

如果经理想将“葡萄”的库存从 1 更改为 11,我应该如何以最简单的方式处理?

【问题讨论】:

  • 在程序中存储三个不同的列表会使这项任务更加困难,更好的数据结构是dictionary,您可以将所有信息存储在一起。有csv.DictReader 方便以这种方式处理您的文件。
  • 您可能应该考虑使用流行的关系数据库(例如 MySQL)来处理此事务,而不是 csv 文件。例如,您将如何处理用户登录和交易?我认为当你这样做时如何改变股票价格也会更清楚。

标签: python python-3.x csv input


【解决方案1】:

由于这似乎是一项家庭作业或练习,因此这不是一个完整的答案,但应该可以帮助您入门。

读取您的文件,使用字典列表来存储项目:

items_in_store = []
import csv
with open('listlist.csv') as csvfile:
    readCSV = csv.reader(csvfile,delimiter=',')
    for row in readCSV:
        item = dict(name=row[0], price=row[1], stock=row[2])
        items_in_store.append(item)

遍历结果列表,更改特定目标项:

tgt_item = 'apple'
tgt_stock = 5
for item in items_in_store:
    if item['name'] == tgt_item:
         # we found our item, change it
         item['stock'] = tgt_stock

persist your changes到文件(注意这次我们以写模式打开文件):

with open('listlist.csv', 'w') as csvfile:
    writeCSV = csv.writer(csvfile, delimiter=',')
    for item in items_in_store:
        row = [item['name'], item['price'], item['stock']]
        writeCSV.writerow(row)

另一种方法,再次读取文件,但这次存储在包含字典的字典中:

items_in_store = {} # create empty dictionary
import csv
with open('listlist.csv') as csvfile:
    readCSV = csv.reader(csvfile,delimiter=',')
    for row in readCSV:
        # use item name as key in first dictionary
        # and store a nested dictionary with price and stock
        items_in_store[row[0]] = dict(price=row[1], stock=row[2])

以这种方式存储我们的数据,我们不需要循环更改库存,我们可以立即使用其密钥访问所需的项目:

tgt_item = 'apple'
tgt_stock = 5
items_in_store[tgt_item]['stock'] = tgt_stock

在上述所有 sn-ps 示例中,您可以要求用户输入来填写您的 tgt_itemtgt_stock

【讨论】:

  • 这只是一个简单的例子,所以我可以用我的代码来解释问题。我试图省略熊猫,因为我想使用列表。我用字典做了和你完全相同的事情,但它不起作用。当我重新打开 CSV 文件时,我想要更改的值仍然相同,并且我希望更改是永久性的。它只在程序运行时改变。
  • @RebecaTeban 这可能是一个愚蠢的问题,但您是否真的在更改后将数据保存回文件?
  • @RebecaTeban 查看编辑以获取使用第一种方法写回更改的简单示例。
【解决方案2】:

例如,您可以使用 pandas 来做到这一点,并且您不需要处理不同的列表

       0         1       2
0   apples      1.00    11
1   grape       1.20    1
2   chocolate   0.75    15
3   bananas     1.35    27


import pandas
df =  pandas.read_csv(csv_file_path, header=None)
df.loc[df[0] == "apples", 2] = new_stock

如果将列名添加到文件中,[0] 和 2 可以通过列名进行更改

【讨论】:

    猜你喜欢
    • 2020-04-27
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2022-01-13
    • 2021-12-02
    • 1970-01-01
    相关资源
    最近更新 更多