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>You'll either have to return to the root directory using as many <code>..</code> as required, store the root directory or specify a full directory from your home:</p>

<pre><code>curr_path = os.getcwd()
os.chdir('Deployment/Work/test2/src')

os.chdir(curr_path)
os.chdir('Deployment/Work/test2/src')
</code></pre>

<p>Or:</p>

<pre><code>os.chdir('Deployment/Work/test2/src')

os.chdir('../../../../Deployment/Work/test2/src') # Not advisable
</code></pre>

<hr>

<p>Instead of the above, you may consider more <em>Pythonic</em> ways to change directories on the fly, like using a <em>context manager</em> for directories:</p>

<pre><code>import contextlib
import os

@contextlib.contextmanager
def working_directory(path):
    prev_cwd = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(prev_cwd)

with working_directory('Deployment/Work/test1/src'):
    names = {}
    for fn in glob.glob('*.c'):

with working_directory('Deployment/Work/test2/src'):
    names = {}
    for fn in glob.glob('*.c'):
        ...
</code></pre>

<p>You simply specify the relative directory from the current directory, and then run your code in the context of that directory. </p>

python