if the 6th element of each row of my file is 2, I want to add 4 to element 10 on the same line. I'm running into problems with addition.
import csv
plusfour=[]
with open("101.txt", 'rb') as f:
reader = csv.reader(f)
# make it into a list
data = list(reader)
# for each line in data
dataline = 0
for i in data:
if data[dataline][5] is "2":
plusfour.append(int(data[dataline][9])+4)
print(plusfour)
#print(data[dataline][9])
dataline +=1
but it won't print anything. I also tried
if data[dataline][5] is "2":
print(data[dataline][9])
and that works, so the issue is with how I'm trying to add 4 to that value. I can't figure out what I'm doing wrong above in specifying data[dataline][9] as an integer that can be added to.
Basically, if the value of one column in my csv is 2, how can I add 4 to the value of another column on the same row? I need to iterate through each row.
here's part of the file I'm loading:
here's the output of my 2nd code snippet:
EDIT: I was having problems because some of my values were blank. I now have this:
import csv
plusfour=[]
# open file with all subjects in it
with open("101.txt", 'rb') as f:
reader = csv.reader(f)
# make it into a list
data = list(reader)
# for each line in data
dataline = 0
valid_responses = ("1", "2")
for i in data:
if data[dataline][5] not in valid_responses:
plusfour.append("NA")
elif int(float(data[dataline][5])) == 2:
# add 4 to value of 10th element in same row
data[dataline][9] = int (float(data[dataline][9]))+4
plusfour.append(data[dataline][9])
print(plusfour)
elif int(float(data[dataline][5])) == 1:
plusfour.append(data[dataline][9])
dataline +=1
and am getting this error: data[dataline][9] = int (float(data[dataline][9]))+4 ValueError: could not convert string to float: