Peter Hartnett Peter Hartnett - 2 years ago 125
Python Question

TypeError: list indices must be integers, not str. Know the issue, not the answer

Unique situation, I know the problem, just dont know a solution.

import string

timefile = open('lasttimemultiple.txt','r+')#opens the file that contains the last time run
lasttime = the last time file
items= int(2)

splitlines = string.split(lasttime,'\n')
print splitlines[items][0:2]
timefile.close() #closes last time
PullType = '00'
datapt = '01'
for items in splitlines:
if splitlines[items][0:2] == PullType:
datapt = splitlines[items]
print ''

print datapt

I know my issue is I am using 'items' as the index I am calling versus an integer, but I don't know how to use a reference to work through the data without using an non-int variable name.

Any ideas how to achieve this?

Answer Source

You should show the actual traceback. If you had, you would have seen that the error is in this line:

if splitlines[items][0:2] == PullType:

That's because items here has been redefined by the for loop in the line before. In a for loop in Python, the variable is not a counter, it is the actual item from that iteration. So, in the first iteration, items is the first element of splitlines, etc. So it is a string, not an integer. The fix is to use it directly:

if items[0:2] == PullType:

(Also, you should think about better variable names: that should be item, not items).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download