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().
os.getcwd()
? – Eamesos.getcwd()
returns the path of the first module, which imported that module, or imported another one which imported it. The first module might be in many directories up or down. So it doesn't seem very elegant to typeos.getcwd()+'something/somethingelse/yetanother/finallyhere'
– Stanwinnos.getcwd()
returns the current working directory of the process, which does not necessarily have anything at all to do with any module at all. – Iniquity