简体   繁体   English

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

[英]Importing modules in Python that use local paths

I have an issue with a module that uses relative paths, the issue is rather simple to explain:我有一个使用相对路径的模块的问题,这个问题很容易解释:

This is my architecture:这是我的架构:

myProject/
├───main.py
│
├───modules/
│   ├───__init__.py
│   ├───files/
│   │    some_text.txt
│   └───module.py

some_text.txt contains some non-relevant text. some_text.txt 包含一些不相关的文本。

module.py contains: module.py包含:

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

and main.py contains:main.py包含:

from modules import module

module.read_file()

When I run main.py , you can obviously expect this error I get:当我运行main.py 时,您显然可以预料到我得到的这个错误:

FileNotFoundError: [Errno 2] No such file or directory: 'files/some_text.txt'

The solution is of course to change the path in module.py to " modules/files/some_text.txt " but I really don't like this solution because it's not intuitive and won't work if I call directly module.py.解决方案当然是将module.py中的路径改为“ modules/files/some_text.txt ”,但我真的不喜欢这个解决方案,因为它不直观,如果我直接调用module.py就行不通。 Also, if I call myProject from another project, it will still fail because I will have to change the path again to " myProject/modules/files/some_text.txt ".另外,如果我从另一个项目调用 myProject ,它仍然会失败,因为我必须再次将路径更改为“ myProject/modules/files/some_text.txt ”。

What are the good practices to solve this problem correctly?正确解决此问题的良好做法是什么?

You can use the __file__ variable (that holds the path to the current script) as a root and build your path based on that.您可以使用__file__变量(保存当前脚本的路径)作为根,并基于此构建您的路径。

In your case在你的情况下

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM