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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…