CSV 如何找到值,并编辑它的值

CSV how to find the value, and edit its value

假设这是在我的 CSV 文件中

Apple        10
Banana       14
Orange       23
Watermelon   54

比方说,这是上周商店里的水果供应量。

所以这周,我得到了 12 个苹果,如果我的水果数量比前一周大,我想用 12 代替 10。这是我目前为止的代码,它将数据放入csv 文件。

def fruit():
    FruitT = input("Please type in the name of the fruit: ")
    FruitN = input("Please type in the amount of the fruit: ")



    f = open('fruitstcok.csv', 'a')
    f.write(FruitT.title()+','+str(FruitN)+'\n')
    f.close()
    print ("Success")
    fruit()

fruit()

如何做到这样,当我输入水果名称和数量时,它会检查数量是否更大,如果是,则替换,如果不是,则什么都不做?

此外,我想知道如何将金额添加到您的 csv 中。

Apple    10,12

所以在这个月的晚些时候,我可以通过将所有水果相加并除以列表中的数字来找出当月水果的平均数量。我可以使用 len 吗?

我当然会创建两个csv文件。到目前为止,我知道如何读取 csv 文件并打印它们。

我建议您从一个非常简单的实现开始,只是为了让您的应用程序正常工作。作为概念证明,只需将其存储在一个简单的 dict.

fruits = [{'num': [10], 'type': 'Apple'}, {'num': [14], 'type': 'Banana'}]

def update_fruits(fruit, num):
    for i in fruits:
        if i['type'] == fruit:
            if i['num'] >= num:
                i['num'].insert(0, num)

通过将项目保留在列表中,您可以在以下时间之后进行计算:

update_fruits('Apple', 12)

print fruits 
# [{'num': [12, 10], 'type': 'Apple'}, {'num': [14], 'type': 'Banana'}]

而如果需要访问当前值,只需获取num

中的第一项

使用泡菜:

import pickle

def fruit():
        try:
            with open('fruits.pickle', 'rb') as f:
                items = pickle.load(f)
        except (ValueError,IOError) as e:
            print(e)
            items =  {'Banana': {'mon': [14], 'count': 14}, 'Apple': {'mon': [10], 'count': 10}, 'Orange': {'mon': [23], 'count': 23}, 'Watermelon': {'mon': [54], 'count': 54}}
        fruit_t = input("Please type in the name of the fruit: ")
        fruit_n = int(input("Please type in the amount of the fruit: "))
        if fruit_t in items:
            items[fruit_t]["mon"].append(fruit_n)
            if items[fruit_t]["count"] < fruit_n:
                items[fruit_t]["count"] = fruit_n
        else: # else add new fruit
            items[fruit_t] = {"mon":[fruit_n],"count":fruit_n}
        with open('fruits.pickle', 'wb') as f:
            pickle.dump(items, f)
        print(items)

正如我在评论中所说,您最初创建项目的方式以及它们所具有的值应该是第一个 运行 的默认值。

您还应该处理用户输入无效项或未输入可转换为 int 的有效值的情况。

最好用小写字母和使用 fruit_t.lower().

加强字典键

打印信息:

for k in items:
     print("{} monthly  {}".format(k,items[k]["mon"]))
     print("{} total {}".format(k,items[k]["count"]))