I try to parse the ini-file ( file variable), but when accessing by index, an exception occurs:

 contFile = file.readlines() print(contFile) # ['[MAIN]\r', '\r\n', 'comments=Test1\r\n'] cont = contFile[1].split('=')[1] # IndexError: list index out of range 

Question: How to get rid of '\r\n' in the list? There is a feeling that they interfere with the execution of the program.

  • can check each list item on .isspace ()? I do not fully understand where the list is there, if it is written to the file. contFile? - spirit
  • contFile is a list of initially consisting of 2 elements ['[MAIN]', 'comments = Test1'], after all not tricky operations it turns out already from 3 itself as indicated above and cont = contFile [1] .split ('=') [1] .replace (self.forIf, textCont) no longer apply here if you don’t get rid of '\ r \ n' - XFixer
  • could advise .strip (), but I think you would have guessed it yourself. - spirit
  • I think the problem lies somewhere in fil.write (''. Join (contFile)) - XFixer
  • .strip () tried not to help (besides this method is applicable to a string variable, but in this case I have an item in the list - XFixer

1 answer 1

Try this:

 contFile = [line for line in contFile if line.strip()] 

And for cutting \ n and \ r from elements already .strip ()

For example:

 cont = contFile[1].strip().split('=')[1].replace(self.forIf, textCont) 

UPD

 In [189]: contFile = ['[MAIN]\r', '\r\n', 'comments=Test1\r\n'] In [190]: contFile = [line.strip() for line in contFile if line.strip()] In [191]: contFile Out[191]: ['[MAIN]', 'comments=Test1'] 
  • Thank you for your option, but did not help ( - XFixer
  • then I don't understand what exactly is needed. Look, I updated the answer. - spirit
  • Yes, your method works I will put +, it may be useful to someone, but unfortunately it did not help me, I probably need to dig deeper into the function itself - XFixer
  • so output intermediate values, or use ipdb (pdb), see what's wrong, if anything - write. - spirit
  • Here I try on yours: 0th iteration ['[MAIN] \ r', '\ r \ n', 'comments = Test1 \ r \ n'] 1st iteration ['[MAIN]', 'comments = Test1 '] 2nd iteration [' [MAIN] comments = Test1 '] It turns out for one-time use, this method is suitable, if further - no - XFixer