I am still very new to Python. I have a large tab delimited text file with a lot of data, and I'm trying to get values from columns 18 and 22 and making a calculation called "rate" which I then want to append to the end of each line in my text file.
I cannot seem to get any attempt at this to work. My attempt is shown below, but I will always get an error (which is in the ouptut shown below my code).
with open(fieldDataFile, 'rw') as f:
lines = f.readlines()[1:]
for i, line in enumerate(lines):
ratecalc = (float(lines[i+1][21]) - float(lines[i][21]))/(float(lines[i+1][17]) - float(lines[i][17]))
line[i] = line[i].strip() + str(ratecalc)
for line in lines:
f.write(line)
Output:
ValueError: could not convert string to float: n
I can't find any letters at all in columns 18 or 22, so I have no idea where this conversion error comes from. Even if the code works, I'm not sure if it would actually append the value.
Any help is greatly appreciated! Thank you!
EDIT: I tried printing out the lines I needed using:
print fieldDataFile
with open(fieldDataFile, 'rw') as f:
lines = f.readlines()[1:]
for i, line in enumerate(lines):
print (lines[i][21])
print (lines[i+1][21])
print (lines[i][17])
print (lines[i+1][17])
with the result:
n
n
i
i
Although according to the data in the file, it should be:
1452.1
1509.5
0
5.52
Unfortunately, I cannot share headers or more info since the file is proprietary, so I know this makes it hard to help. However, I don't notice anything particularly wrong with it, since it has headers like any other file and columns of numbers below each one in a tab delimited format.