Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

python - IndexError: string index out of range:

I'm trying take a .txt file populated by 88 rows, each of which has two characters separated by a space, copy the first character in each row into a list #1, copy the second character of each list into a list #2 and then populate a dictionary with those two lists. Something, however, is going wrong when I try to copy down the data from the file into my lists. Could you tell me what I'm not doing correctly?

I keep getting this error: "IndexError: string index out of range" at the line where I have typed "column1[count] = readit[0]"

def main():

    modo = open('codes.txt', 'r')       #opening file
    filezise = 0                        #init'ing counter
    for line in modo:
        filezise+=1                     #counting lines in the file
    column1 = []*filezise
    column2 = []*filezise               #making the lists as large as the file
    count = 0                           #init'ing next counter
    while count < filezise+1:
        readit = str(modo.readline())
        column1[count] = readit[0]      ##looping through the file and
        column2[count] = readit[2]      ##populating the first list with the
        count+=1                        #first character and the second list       
    print(column1, column2)             #with the second character     
    index = 0                               
    n = 0
    codebook = {}                       #init'ing dictionary
    for index, n in enumerate(column1): #looping through to bind the key
        codebook[n] = column2[index]    #to its concordant value
    print(codebook)
main()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you write

 for line in modo:
        filezise+=1  

You have already consumed the file. If you want to consume it again, you need to do modo.seek(0) first to rewind the file back.

If you do not rewind the file, the line below will return an empty string, because there is nothing left in the file.

readit = str(modo.readline())

Of course, there's no real need to go through the file twice. You can just do it once and append to your lists.

column1 = []
column2 = []
for line in modo:
   filezise+=1
   column1.append(line[0])
   column2.append(line[2])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...