Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
导入Python中使用本地路径的模块_Python_Path_Python Import - Fatal编程技术网

导入Python中使用本地路径的模块

导入Python中使用本地路径的模块,python,path,python-import,Python,Path,Python Import,我对使用相对路径的模块有一个问题,这个问题很容易解释: 这是我的架构: myProject/ ├───main.py │ ├───modules/ │ ├───__init__.py │ ├───files/ │ │ some_text.txt │ └───module.py some_text.txt包含一些不相关的文本 模块。py包含: def read_file(): with open("files/some_text.txt",&qu

我对使用相对路径的模块有一个问题,这个问题很容易解释:

这是我的架构:

myProject/
├───main.py
│
├───modules/
│   ├───__init__.py
│   ├───files/
│   │    some_text.txt
│   └───module.py
some_text.txt包含一些不相关的文本

模块。py包含:

def read_file():
    with open("files/some_text.txt","r") as f:
        print(f.read())
from modules import module

module.read_file()
main.py包含:

def read_file():
    with open("files/some_text.txt","r") as f:
        print(f.read())
from modules import module

module.read_file()
当我运行main.py时,您显然可以预期我会出现以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'files/some_text.txt'
解决方案当然是将module.py中的路径更改为“modules/files/some_text.txt”,但我确实不喜欢这个解决方案,因为它不直观,如果我直接调用module.py,它将无法工作。另外,如果我从另一个项目调用myProject,它仍然会失败,因为我必须再次将路径更改为“myProject/modules/files/some_text.txt”


正确解决此问题的最佳做法是什么?

您可以使用
\uuuu file\uuu
变量(保存当前脚本的路径)作为根,并基于此构建路径

就你而言

"files/some_text.txt"
# can become
os.path.join(os.path.dirname(__file__), 'files', 'some_text.txt')