how to iterate over files in neighbouring dir
<p>I have a project structure like this</p>

<pre><code>test/foo.py
test/bar (directory with 10 files)
src/
README.MD
</code></pre>

<p>From <code>foo.py</code> (which is in <code>test</code> dir), I wish to iterate over the 10 files in the <code>bar</code> dir (which is also in <code>test</code> dir). I tried to do this</p>

<pre><code>import os

for path in os.listdir('bar'):
    etc
</code></pre>

<p>But it says, "no such file or directory: bar"</p>

<p>I then tried to do this</p>

<pre><code>basepath = '/Users/me/pythonprojects/project_x/bar' 
for path in os.listdir(basepath):
    etc
</code></pre>

<p>However, when I counted over the number of files it iterated over, it was 0 (Not the expected 10).</p>

<p>I then tried to do this</p>

<pre><code>   for path in '/Users/me/pythonprojects/project_x/test/bar':
       etc
</code></pre>

<p>However, it then iterated over every file in my system (hundreds, not just the 10 in bar).</p>

<p>Although this is not what I wish to do, if from the command line I pass an argument of <code>.</code> to sys.argv[1] and then try to iterate over the bar dir like this</p>

<pre><code>for path in sys.argv[1]
</code></pre>

<p>It iterates over the ten files in the bar dir.</p>

<p>So, is there a way from <code>foo.py</code> to iterate over the files in <code>bar</code> (and only the files in <code>bar</code> dir)</p>

<p>Update, when I do <code>print(os.getcwd(), "foo.py cwd")</code> in <code>foo.py</code> (and then call the test runner from <code>run_test.py</code> in root), it says</p>

<pre><code>/Users/me/pythonprojects/project_x
</code></pre>

<p>i.e. <code>os.getcwd()</code> doesn't recognize that <code>foo.py</code> is in <code>test</code> dir of the project, which may be because the test is run from root?</p>

<p>Use functions in <code>os.path</code> to do this (works only from a script, not REPL):</p>

<pre><code>import os

# retrieve path to directory with script
script_dir = os.path.dirname(os.path.realpath(__file__))

bar_dir = os.path.join(script_dir, 'bar')

for f in os.listdir(bar_dir):
    print(f)
</code></pre>

python