【问题标题】:How to load a file in module without hard coding path [duplicate]如何在没有硬编码路径的模块中加载文件[重复]
【发布时间】:2021-05-20 17:34:44
【问题描述】:

假设我在一个名为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.pymy_functions 不在同一目录中。我尝试使用here 中的这一行来欺骗func1 来定义它的相对路径,但即使这样也将路径定义为calling_code.py 的目录。

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

我唯一能想到的另一件事是在func1 中加载my_functions.py,这样我就可以将其称为__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()

虽然这行得通,但它看起来有点像 hack。有没有其他方法可以解决这个问题?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    这是一个设计问题。如果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
      

    【讨论】:

    • 好吧,我试图避免对路径进行硬编码,因为我在不同的系统(不同的服务器在不同的时间)上使用了这个模块,所以我试图避免每次导出时都重写路径模块到新的/不同的服务器(或在本地使用)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多