在以下代码中,如何转义处理print int(value) - int(dict2[key])
的第一行?
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 :(得分:2)
跳过第一行:
csv_reader1 = csv.reader(file1)
next(csv_reader1) # skip 1st row
csv_reader2 = csv.reader(file2)
next(csv_reader2) # skip 1st row
答案 1 :(得分:2)