2016-08-04 25 views
0

我遇到了麻煩,想方法是將csv文件中某個行的數據更改爲通過腳本本身分配​​的新值。python中的CSV數據庫樣式更改就像將數據切換到文件中一樣

我希望你們能幫我解決這個問題。 這裏是我的代碼:

import csv 

def Toevoeging_methode_plus(key_to_find, definition): 
    if key_to_find in a: 
     current = a[key_to_find] 
     a[key_to_find] = int(current) + aantaltoevoeging 


def Toevoeging_methode_minus(key_to_find, definition): 
    if key_to_find in a: 
     current = a[key_to_find] 
     a[key_to_find] = int(current) - aantaltoevoeging 
a = {} 


with open("variabelen.csv") as csvfile: 
    reader = csv.DictReader(csvfile) 
    for row in reader: 
     a[row['Product']] = row['Aantal'] 
     print a 

print(""" 
1. Toevoegen 
2. Aftrek 
3. Check 
""") 
askmenu = int(raw_input("Menu Nummer? ")) 
if askmenu is 1: 
    toevoegproduct = raw_input("Productnummer > ") 
    aantaltoevoeging = int(raw_input("Hoeveel > ")) 
    Toevoeging_methode_plus(toevoegproduct, aantaltoevoeging) 
    print a 

elif askmenu is 2: 
    toevoegproduct = raw_input("Productnummer > ") 
    aantaltoevoeging = int(raw_input("Hoeveel > ")) 
    Toevoeging_methode_minus(toevoegproduct, aantaltoevoeging) 
    print a 

elif askmenu is 3: 
    checknummer = raw_input("Productnummer > ") 
    if checknummer in a: 
     print a[checknummer] 

else: 
    print "oops" 
+0

使用熊貓庫在python –

+0

你可以發佈你的樣本行r'variabelen .csv'? – haifzhan

+0

@HaifengZhang https://gyazo.com/29c8e2b4a039bb1b8789b59be1bc935e –

回答

0

我從你提供的鏈接做了一個CSV文件variabelen.csv(你需要轉換到你的Excel文件爲CSV文件)。

Product,Aantal 
233,60 
2234,1 

我加逗號分隔符在with open塊:

with open("variabelen.csv") as csvfile: 
    reader = csv.DictReader(csvfile, delimiter=',') 
    for row in reader: 
     a[row['Product']] = row['Aantal'] 
     print a 

輸出:

{'233': '60'} 
{'2234': '1', '233': '60'} 

1. Toevoegen 
2. Aftrek 
3. Check 

Menu Nummer? 1 
Productnummer > 233 
Hoeveel > 1 
{'2234': '1', '233': 61} 

現在的233值成爲61預計

相關問題