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>I suppose the script is not working because you are trying to change the directory using a relative path. This means that when you execute the first <code>os.chdir</code> you change your working directory from the current one to <code>'Deployment/Work/test1/src'</code> and when you call <code>os.chdir</code> the second time the function tries to change working directory to <code>'Deployment/Work/test1/src/Deployment/Work/test2/src'</code> that I suppose is not what you want.</p>

<p>To solve this you can either use an absolute path:</p>

<p><code>os.chdir('/Deployment/Work/test1/src')</code></p>

<p>or before the first <code>os.chdir</code> you could keep track of your current folder:</p>

<p><code>current = os.getcwd()
os.chdir('Deployment/Work/test1/src')
...
os.chdir(current)
os.chdir('Deployment/Work/test2/src')</code></p>

python