如何使一个“始终相对于当前模块”的文件路径?

假设您有一个包含

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

并且‘ test.txt’文件在同一个文件夹中。

现在,假设您从另一个文件夹中的另一个模块导入该模块。该文件不会在与该代码所在的模块相同的文件夹中进行搜索。

那么,如何使模块搜索文件的相对路径在同一个文件夹首先?

使用“ __file__”或“ os.getcwd()”有多种解决方案,但我希望有一种更简洁的方法,比如在传递给 open ()或 file ()的字符串中使用相同的特殊字符。

30771 次浏览

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

import os


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

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.

Note that when you're working with a Python package, there are better approaches available for reading resources - you could consider moving to importlib-resources. This requires Python 3.7+, for older versions you can use pkgutil. One advantage of packaging the resources correctly, rather than joining data files relative to the source tree, is that the code will still work in cases where it's not extracted on a filesystem (e.g. a package in a zipfile). See How to read a (static) file from inside a Python package? for more details about reading/writing data files in a package.