我想创建一个名为 unifile
的工具来保存和打开文件
像这样 unifile.open.yaml("file.yaml")
。
这是我的结构:
unifile
|
├-open
| └--__init__.py
|
└-save
└--__init__.py
调用我的模块的代码:
import unifile
a = unifile.open.yaml("file.yaml")
打开/初始化.py
import yaml
class open():
def yml(self, file_path):
try:
with open(file_path, "r", encoding="utf-8") as yaml_conf:
yaml_file = yaml.safe_load(yaml_conf)
return yaml_file
except OSError:
print("Can't load yaml")
如果我导入 unifile
总是出现 1 个错误:
module unifile has no atribute open
2 __init__.py 中的错误
我无法打开文件
[pylint] Context manager 'open' doesn't implement enter and exit. [not-context-manager]
最佳答案
在这里添加您的问题的解决方案,使您的项目结构如下。
在 unifile 本身而不是其他模块中添加 unifile/__init__.py
文件。
然后是unifile/open/_open.py
文件内容
import yaml
class Open():
def __init__(self):
pass
def yml(self, file_path):
try:
with open(file_path, "r", encoding="utf-8") as yaml_conf:
yaml_file = yaml.safe_load(yaml_conf)
return yaml_file
except OSError:
print("Can't load yaml")
unifile/__init__.py
文件的内容
from .open._open import Open
在终端中像这样运行程序
另外,最好先创建一个对象元素,然后再继续。
关于python - 创建 Python 子模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58393436/