Reputation: 7280
I'm getting the IndexError: string index out of range. Each line in the file "document_words" ends with "-99". So i think error may be because "-99" is not converted to int. But i'm not sure. If that is the case how can i convert "-99" to int and break from the loop.
Following is my code:
words=open('words','r')
image=open('document_words','r')
data=open('input','a')
linecount=0
for line in image:
if line.strip():
linecount+=1
image.read()
image.seek(0,0)
while linecount>0:
line1=image.readline().split()
for entry in line1:
num=int(entry)
if (num<0):
print("break from loop")
break
else:
tag=words.readline()[num]
data.write(str(tag)+' ')
data.write('\n')
linecount=linecount-1
data.flush()
data.close()
words.close()
image.close()
Upvotes: 0
Views: 1000
Reputation: 304147
You haven't told us which line fails, but this looks like the obvious one
tag = words.readline()[num]
so num
is outside the bounds. I don't think it is the -99
because it should break in that case. You can add a try/except to help track it down
try:
tmp = words.readline()
tag = tmp[num]
except IndexError, e:
print tmp, num
EDIT: Looks like you are mixing tabs and spaces for the indenting. This is a no-no unless you are using 8 character tab-stops
Upvotes: 1