IndexError:字符串索引超出范围: [英] IndexError: string index out of range:

查看:49
本文介绍了IndexError:字符串索引超出范围:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一个由88行填充的.txt文件,每个文件有两个字符,两个字符之间用空格隔开,将每行的第一个字符复制到列表#1中,将每个列表的第二个字符复制到列表中列表#2,然后用这两个列表填充字典.但是,当我尝试将文件中的数据复制到列表中时,出现了问题.你能告诉我我做错了什么吗?

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?

在输入"column1 [count] = readit [0]"的行,我不断收到此错误:"IndexError:字符串索引超出范围"

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()

推荐答案

撰写时

 for line in modo:
        filezise+=1  

您已经使用了该文件.如果要再次使用它,则需要先执行 modo.seek(0)将文件后退.

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])

这篇关于IndexError:字符串索引超出范围:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆