1

I am trying to execute a python script which is giving me an IndexError. I understood that the rsplit() method failed to split the string. I don't exactly know why it is showing index out of range. Could anyone tell me how to solve this problem ?

code

raw_directory = 'results/'
for name in glob.glob(raw_directory + '*.x*'):
        try:
                #with open(name) as g:
                #       pass
                print(name)
        reaction_mechanism = 'gri30.xml' #'mech.cti'
        gas = ct.Solution(reaction_mechanism)
        f = ct.CounterflowDiffusionFlame(gas, width=1.)
        name_only = name.rsplit('\\',1)[1] #delete directory in filename
        file_name = name_only
        f.restore(filename=raw_directory + file_name, name='diff1D', loglevel=0)

Output

If I delete the file strain_loop_07.xml, I got the same error with another file.

results/strain_loop_07.xml
Traceback (most recent call last):
   File "code.py", line 38, in <module>
     name_only = name.rsplit('\\'1)[1] #delete directory in filename
IndexError: list index out of range
spkumar
  • 15
  • 4

1 Answers1

0

If rsplit failed to split the string, it returns an array with only one solution, so the [0] and not [1]

I understood in reply of this post that "name" variable is filled with text like "result/strain_loop_07.xml", so you want to rsplit that, with a line more like

name_only = name.rsplit('/', 1)[1]

So you'll get the "strain_loop_07.xml" element, which is what you probably wanted, because name.resplit('/', 1) return something like

['result', 'strain_loop_07.xml']

By the way, don't hesitate to print your variable midway for debuging, that is often the thing to do, to understand the state of your variable at a specific timing. Here right before your split !

Zartant
  • 109
  • 9
  • Okay. I have to organize the data from the files which are already generated with another script. Might there by any issue with those files representation ? I am using python for the first time so don't have any experience in debugging. Can you give me any hint or solution ? – spkumar Feb 13 '21 at 08:43
  • I advise you to print what you already have here. For instance, at the line before the rsplit, put the line "print(name)" , you can comment the line after that for now, just to see what is the exact formation of name you'll have. Perhaps you will understand something unexpected :D Also if you have something interesting are you are still in trouble, you can edit your main post with your new discoveries – Zartant Feb 13 '21 at 09:02
  • Okay. I will edit the main post if I get something strange. After adding print(name), I got one more extra line in the output i.e. results/strain_loop_07.xml – spkumar Feb 13 '21 at 09:13
  • So you say it prints "result/strain_loop_07.xml" ? Then if you have result of that nature, don't you want your rsplit to have the parameter "/" instead of "\\" ? – Zartant Feb 13 '21 at 09:24