Leahcim Leahcim - 3 months ago 7
Python Question

how to iterate over files in neighbouring dir

I have a project structure like this

test/foo.py
test/bar (directory with 10 files)
src/
README.MD


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

import os

for path in os.listdir('bar'):
etc


But it says, "no such file or directory: bar"

I then tried to do this

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


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

I then tried to do this

for path in '/Users/me/pythonprojects/project_x/test/bar':
etc


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

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

for path in sys.argv[1]


It iterates over the ten files in the bar dir.

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

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

/Users/me/pythonprojects/project_x


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

Answer

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

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)