[英]IndexError: string index out of range:
我正在尝试使用一个由88行填充的.txt文件,每行包含两个以空格分隔的字符,将每行中的第一个字符复制到列表#1中,将每个列表的第二个字符复制到列表#2中然后使用这两个列表填充字典。 但是,当我尝试将文件中的数据复制到我的列表中时,有些东西出错了。 你能告诉我我做得不对吗?
我一直收到这个错误:“IndexError:string index out of range”在我输入的行“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)
退文件。
如果您不倒回文件,下面的行将返回一个空字符串,因为文件中没有任何内容。
readit = str(modo.readline())
当然,没有必要经过两次文件。 您可以只执行一次并附加到列表中。
column1 = []
column2 = []
for line in modo:
filezise+=1
column1.append(line[0])
column2.append(line[2])
尝试这个
codebook = dict([''.join(line.strip().split(' ')) for line in open('codes.txt').readlines()])
您收到错误,因为column1 = []*filezise
实际上不会生成长度filezise的列表。 (如果查看结果,您将看到column1
只是一个空列表。)当您尝试在count > 0
时访问column1[count]
时,您将收到该错误,因为column1
没有任何索引大于0。
您不应该尝试初始化列表。 相反,迭代文件中的行并附加适当的字符:
column1=[]
column2=[]
for line in file('codes.txt'):
column1.append(line[0])
column2.append(line[2])
只要不使用中间列表,您也可以使用字典理解来一次完成所有操作。
with open('codes.txt', 'r') as f:
codebook = {line[0]: line[-1] for line in f.read().splitlines()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.