【发布时间】: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.py 与my_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