D
D
Dmitry Shevchenko2020-08-20 21:53:06
Python
Dmitry Shevchenko, 2020-08-20 21:53:06

Error IndexError: list index out of range, but such an index exists!?

here is part of the code:

def read (self):
        base = open(str(self.base_name), 'r')
        base_r = base.readlines()
        base.close()
        dict_r = {}
        tx=0
        while tx <len(base_r)  :
           base_re = base_r[tx]
           st1 = base_re.split (':')
           print ('st - ',st1)
           #print(str(st1[0]),str(st1[1][:-1]))
           dict_r [st1[0]] = str(st1[1])[:-1]
           tx+=1

I have a text file where each line contains a dictionary written as key:value , st1 is my string that I iterate over and when I output it to the console I get - ['key', 'value\n'] i.e. everything is correct, I split the string into before : and after : , but when I assign dict_r [st1[0]] value to str(st1[1])[:-1] - error , [:-1] in order to \n cut

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Karbivnichy, 2020-08-20
@ZER0x32

Most likely an error in the text file. Perhaps the structure of the file is broken (for example, there is no colon in one line).

def read (filename):
        base = open(filename, 'r')
        base_r = base.readlines()
        base.close()
        dict_r = {}
        tx=0
        while tx <len(base_r)  :
           base_re = base_r[tx]
           st1 = base_re.split (':')
           print ('st - ',st1)
           # print(str(st1[0]),str(st1[1][:-1]))
           dict_r [st1[0]] = str(st1[1])[:-1]
           tx+=1
        print('*'*20)
        print(dict_r)

read('1.txt')

1.txt
hello:hello2
hello9:hello235345
hello8:hello275
hello7:hello2432
hello6:hello2873

st -  ['hello', 'hello2\n']
st -  ['hello9', 'hello235345\n']
st -  ['hello8', 'hello275\n']
st -  ['hello7', 'hello2432\n']
st -  ['hello6', 'hello2873']
********************
{'hello': 'hello2', 'hello9': 'hello235345', 'hello8': 'hello275', 'hello7': 'hello2432', 'hello6': 'hello287'}

Solution:
The problem was that the text file had extra empty lines at the end:
5f3f9950515d3060413442.png
In this case, there are several solutions:
1) Check for empty lines;
2) Use the try...except;
3) Manually remove the extra empty line at the end of the file;
4) ...

S
soremix, 2020-08-20
@SoreMix

[:-1] in order to \n trim

https://pythonz.net/references/named/str.strip/
dict_r [st1[0]] = st1[1].strip()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question