-1

In the following code how can I escape processing the first rows for 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 is :

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

and file2.csv is:

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

I am trying to subtract the age of person and his/her pet if it appears in both CSVs but I get the following error because it processes the first row as well:

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
Mona Jalal
  • 29,571
  • 61
  • 202
  • 359

2 Answers2

2

Skip the first rows:

csv_reader1 = csv.reader(file1)
next(csv_reader1) # skip 1st row
csv_reader2 = csv.reader(file2)
next(csv_reader2) # skip 1st row
Daniel
  • 40,885
  • 4
  • 53
  • 79
2

To skip the first line use next() then continue your code:

next(csv_reader1, None)

This is a dupe of this question

Community
  • 1
  • 1
EoinS
  • 5,106
  • 1
  • 17
  • 31