python - 如何在没有硬编码路径的模块中加载文件
问题描述
假设我在一个名为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.py
,func1
这样我就可以称它为__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()
虽然这有效,但它似乎有点像黑客。还有其他方法可以解决这个问题吗?
解决方案
这是一个设计问题。如果 的位置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
推荐阅读
- sql - 如何将 SQL 查询的结果导出为 csv 样式的格式化字符串,稍后将其保存到 Oracle 中的 clob 中?
- android - 是否可以同时录制来自多个麦克风的音频?
- python - 如何将具有特定特征的行附加到组的末尾?
- visual-c++ - 如何使用动态分配的结构数组来满足 C6011 错误
- ajax - 带有数组参数的 Spring Boot Ajax GET 请求,作为列表接收:“未找到接口 java.util.List 的主要或默认构造函数”
- google-apps-script - 如何将 GmailApp.search 与变量一起使用?
- c++ - 使用 C++ 编译和链接 curl 简单接口
- android - 如何修复错误以在android中运行jsoup
- dialogflow-es - 在代理回复前等待几秒钟
- c++ - 如何在 Qt 中的类之间发送变量