CSV如何查找值,并编辑其值

时间:2015-02-03 20:00:29

标签: python python-3.x

让我们说这是我的CSV文件

Apple        10
Banana       14
Orange       23
Watermelon   54

让我们说,这是上周在商店里供应的水果。

所以这个星期,我有12个Apple,如果我的水果数量比前一周大,我想这样做它用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文件并打印它们。

2 个答案:

答案 0 :(得分:2)

使用泡菜:

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"])) 来更好地强化dicts键。

打印信息:

{{1}}

答案 1 :(得分:0)

我建议你从一个非常简单的实现开始,只是为了使你的应用程序工作。作为概念验证,只需将其存储在简单的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

中的第一项