Frage

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()
War es hilfreich?

Lösung

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

Andere Tipps

Try this

codebook =  dict([''.join(line.strip().split(' ')) for line in open('codes.txt').readlines()])

You are getting the error because column1 = []*filezise doesn't actually make a list of length filezise. (If you look at the result, you will see that column1 is just an empty list.) When you try to access column1[count] when count > 0, you will get that error because there is nothing in column1 with an index greater than 0.

You shouldn't be trying to initialize the list. Instead, iterate over the lines in the file and append the appropriate characters:

column1=[]
column2=[]
for line in file('codes.txt'):
    column1.append(line[0])
    column2.append(line[2])

There's a much simpler way to get a dictionary from your file, by using the csv module and the dict() built-in function:

import csv

with open('codes.txt', 'rb') as csvfile:
    codebook = dict(csv.reader(csvfile, delimiter=' '))

So long as the intermediate lists aren't being used, you could also use a dictionary comprehension to do everything in one go.

with open('codes.txt', 'r') as f:
    codebook = {line[0]: line[-1] for line in f.read().splitlines()}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top