根据用户输入更改现有CSV文件

问题描述 投票:0回答:2

我会尽量保持这个尽可能简短,因为我试图找到答案而我却做不到。我正在尝试创建一个简单的直到系统。我使用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))

如果经理想要将项目'grape'的库存从1更改为11,那么我该如何以最简单的方式处理?

python python-3.x csv input
2个回答
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

在上面的所有示例片段中,您可以要求用户输入来填充您的tgt_itemtgt_stock


0
投票

你可以使用熊猫这样做,你不需要处理不同的列表

       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

© www.soinside.com 2019 - 2024. All rights reserved.