How to change directories within Python?
<p>I have the following code. It works for the first directory but not the second one...
What I am trying to do is to count the lines on each of the files in different directory.</p>

<pre><code>import csv
import copy
import os
import sys
import glob

os.chdir('Deployment/Work/test1/src')
names={}
for fn in glob.glob('*.c'):
    with open(fn) as f:
        names[fn]=sum(1 for line in f if line.strip() and not line.startswith('/') and not line.startswith('#') and not line.startswith('/*')and not line.startswith(' *'))    

print ("Lines test 1 ", names)
test1 = names

os.chdir('Deployment/Work/test2/src')
names={}
for fn in glob.glob('*.c'):
    with open(fn) as f:
        names[fn]=sum(1 for line in f if line.strip() and not line.startswith('/') and not line.startswith('#') and not line.startswith('/*')and not line.startswith(' *'))    

print ("Lines test 2 ", names)
test2 = names

print ("Lines ", test1  + test2)
</code></pre>

<p>Traceback:</p>

<pre><code>FileNotFoundError: [WinError 3] The system cannot find the path specified: 'Deployment/Work/test2/src'
</code></pre>

<p>Your <code>os.chdir</code> is interpreted relative to the current working directory. Your first <code>os.chdir</code> changes the working directory. The system tries to find the second path relative to the first path.</p>

<p>There are several ways to solve this. You can keep track of the current directory and change back to it. Else make the second <code>os.chdir</code> relative to the first directory. (E.g. <code>os.chdir(../../test2/src')</code>. This is slightly ugly. A third option is to make all paths absolute instead of relative.</p>

python