首页 > 解决方案 > 如何在没有硬编码路径的模块中加载文件

问题描述

假设我在一个名为my_functions.py. 这些函数之一必须从与my_functions.py. 例如:

# contents of my_functions.py
def func1():
    # first thing, load a file in same directory as my_functions.py
    data = open("blah.txt", "r").read()

如果我导入my_functions然后calling_code.py调用func1,我会收到一条错误消息,告诉我blah.txt不是文件。发生这种情况是因为calling_code.py与 不在同一目录中my_functions我尝试使用此处func1的这一行来欺骗定义它的相对路径,但即使这样也将路径定义为's 目录。calling_code.py

__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))

我能想到的唯一另一件事是加载my_functions.pyfunc1这样我就可以称它为__file__属性。例如

# contents of my_functions.py
def func1():
    # load my_functions.py
    import my_functions as mf
    root = os.path.dirname(my_functions.__file__)
    src = os.path.join(root, "blah.txt")

    # load a file in same directory as my_functions.py
    data = open(src, "r").read()

虽然这有效,但它似乎有点像黑客。还有其他方法可以解决这个问题吗?

标签: pythonpython-3.x

解决方案


这是一个设计问题。如果 的位置blah.txt相对于 是固定的my_functions.py,则func1不能使用硬编码的相对路径,因为它与工作目录有关,而不是与源代码的位置有关。

如果您不想使用__file__,其他解决方案是:

  • 将路径blah.txt作为参数传递给func1

    def func1(blah_path):
        data = open(blah_path, "r").read()
    
  • 使用环境变量指定路径blah.txt

    import os
    
    def func1():
        data = open(os.environ["FUNC1_BLAH_PATH"], "r").read()
    
  • 替换blah.txt为包含数据的模块并使用相对导入:

    from . import blah
    
    def func1():
        data = blah.data
    

推荐阅读