relative directory python

Hi: I want to read files from the directory beneath that where the python program resides.
This is in windows XP
The code reads for the current directory:
files = [f for f in os.listdir('.') if os.path.isfile(f)]
but I want to read the directory 'import' off the current.
I have tried /import; /import/;./import; and ./import/!
I either get a warning that directory does not exist or the program executes with nothing returned. It does work when I copy the files into the current directory so the program is OK!
The directories and files are stored on a server, the program run from a local PC
Does anybody know how to set a different directory when reading in python?
Richard TeasdaleFinancial ControllerAsked:
Who is Participating?
gelonidaConnect With a Mentor Commented:
There are two different directories.
1) The directory in which your python script resides in
2) the current working directory

these directories are not necessarily the same though the are in many cases

For 1)
import os
mydir = os.dirname(__file__)
import_dir = os.path.join(mydir, 'import')
# next line only required of your script changes the working directory
import_dir = os.path.realpath(import_dir)

Open in new window

for 2)
import_dir = 'import'

Open in new window

and then
files = [f for f in os.listdir(import_dir) 
    if os.path.isfile(os.path.join(import_dir, f))]

Open in new window

as you have to check the files presence in the directory you're interested in and not in the current dir.

Depending on your exact needs you might also consider looking at
os.walk(), which directly separates files and directories, though it descends recursively into any other subdirectories
Richard TeasdaleFinancial ControllerAuthor Commented:
Thank you very much!
... should be os.path.dirname(__file__)
thanks pepr. You always get me if I post unverified code ;-)
Oh, no! I was just surprised the function exits (and searched in the doc). It looked a bit strange to me ;)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.