2016-05-31 35 views
0

在下面的代碼中,如何處理print int(value) - int(dict2[key])的第一行?未處理CSV中的第一行

file1 = open("file1.csv", "r") 
file2 = open("file2.csv", "r") 

csv_reader1 = csv.reader(file1) 
csv_reader2 = csv.reader(file2) 

dict1 = {} 
for row in csv_reader1: 
    dict1[row[0],row[1]] = row[2] 
dict2 = {} 
for row in csv_reader2: 
    dict2[row[0],row[1]] = row[3] 

for key, value in dict1.iteritems(): 
    print key, value 

for key, value in dict2.iteritems(): 
    print key, value 

for key, value in dict1.iteritems(): 
    if key in dict2.keys(): 
     print int(value) - int(dict2[key]) 

file1.csv是:

name, last_name, age, city, birthday, date 
mona, jalal, 28, Madison, 7/23/1987, 5/31/2016 
james, cardel, 29, DC, 7/23/1986, 5/1/2016 
kate, spade, 30, NYC, 7/32/1985, 5/24/2016 

和file2.csv是:

name, last_name, pet, pet_age 
mona, jalal, cat, 2 
kate, spade, dog, 3 
mina, nik anjam, bird, 1 

我想減去的人的年齡,如果它出現在他/她的寵物兩個CSV,但我得到以下錯誤,因爲它處理第一行以及:

Traceback (most recent call last): 
26 
    File "/Users/mona/PycharmProjects/PythonCodes/CSV_calculation.py", line 27, in <module> 
27 
    print(int(value) - int(dict2[key])) 
ValueError: invalid literal for int() with base 10: 'age' 

Process finished with exit code 1 
+0

使用欺騙csv.DictReader它會真的很容易使用名稱映射 –

+0

我想創建字典我自己不要使用.DictReader @Apero –

回答

2

要跳過第一行用下一個(),然後繼續你的代碼:

next(csv_reader1, None) 

這是this question

+2

'None'參數可以保護您在文件爲空時觸發'StopIteration'。 –

+0

感謝有關'None'的詳細信息 –

2

跳過第一行:

csv_reader1 = csv.reader(file1) 
next(csv_reader1) # skip 1st row 
csv_reader2 = csv.reader(file2) 
next(csv_reader2) # skip 1st row