How to make an "always relative to current module" file path?

user975135 picture user975135 · Apr 16, 2012 · Viewed 19.4k times · Source

Let's say you have a module which contains

myfile = open('test.txt', 'r')

And the 'test.txt' file is in the same folder. If you'll run the module, the file will be opened successfully.

Now, let's say you import that module from another one which is in another folder. The file won't be searched in the same folder as the module where that code is.

So how to make the module search files with relative paths in the same folder first?

There are various solutions by using "__file__" or "os.getcwd()", but I'm hoping there's a cleaner way, like same special character in the string you pass to open() or file().

Answer

yak picture yak · Apr 16, 2012

The solution is to use __file__ and it's pretty clean:

import os

TEST_FILENAME = os.path.join(os.path.dirname(__file__), 'test.txt')