How to make an “always relative to current module” file path?

喜欢而已 提交于 2019-11-26 20:18:23

问题


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().


回答1:


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

import os

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



回答2:


For normal modules loaded from .py files, the __file__ should be present and usable. To join the information from __file__ onto your relative path, there's a newer option than os.path interfaces available since 2014:

from pathlib import Path

here = Path(__file__).parent
fname = here/'test.txt'
with fname.open() as f:
    ...

pathlib was added to Python in 3.4 - see PEP428. For users still on Python 2.7 wanting to use the same APIs, a backport is available.

Users interested to apply the most modern approaches available should consider moving to importlib-resources rather than joining data files relative to the source tree. Currently, few users have the luxury of restricting compatibility to Python 3.7+ only, so I mention this as a heads-up to those who like to be at the cutting edge.



来源:https://stackoverflow.com/questions/10174211/how-to-make-an-always-relative-to-current-module-file-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!