Python:Changing path at the end of if statement
<p>My gui currently has a combo box with the the option of selecting four different file locations. Once its selected every file in that directory will be displayed in a listbox:</p>

<pre><code>def ComboBox(self, event):
    current = self.buttonChoice.current()

    if (current == 0):
        self.lb.delete(0, END)
        for i in range(0, length1):
            self.lb.insert(END, self.files1[i])

    elif (current == 1):
        self.lb.delete(0, END)
        sys.path.insert(0, sys.path[0]+ "\\folder1")
        for i in range(0, length2):
             self.lb.insert(END, self.files2[i])


    elif (current == 2):
        self.lb.delete(0, END)
        sys.path.insert(0, sys.path[0]+ "\\folder2")
        for i in range(0, length3):
            self.lb.insert(END, self.files2[i])


    elif (current == 3):
        self.lb.delete(0, END)
        sys.path.insert(0, sys.path[0]+ "\\folder3")
        for i in range(0, length4):
            self.lb.insert(END, self.files4[i])
</code></pre>

<p>However my pathing isnt optimal since the function does not return to the parent directory and is instead stuck in that folder(example if current==1 the directory will be in ...\folder1). To get this working i need to move down one directory at the end of each statement. Ive looked at related question and came across     <code>os.chdir('..')</code>. For some reason im having trouble implementing this. Any ideas of how i can move down one directory at the end of each statement.</p>

<p>How about this?</p>

<pre><code>example_dir = r'C:\Users\****\Desktop\PythonScripts\ResidualCreation'

def move_back_dir(a_dir, steps=1):
    return '\\'.join(a_dir.split('\\')[:-steps])

print(move_back_dir(example_dir))     # -&gt; C:\Users\****\Desktop\PythonScripts
print(move_back_dir(example_dir, 2))  # -&gt; C:\Users\****\Desktop
</code></pre>

<hr>

<p>Or as suggested in the comments implement the <code>os.path.dirname()</code> in a recursive way as follows:</p>

<pre><code>def move_back_dir(a_dir, steps=1):
    for i in range(steps):
        a_dir = os.path.dirname(a_dir)
    return a_dir

print(move_back_dir(example_dir))     # -&gt; C:\Users\****\Desktop\PythonScripts
print(move_back_dir(example_dir, 2))  # -&gt; C:\Users\****\Desktop
</code></pre>

<hr>

<p>If setting the number of folders you want to go back (<code>step</code> in example above) is not required simply do <code>os.path.dirname(filename)</code></p>

python python-3.x tkinter sys