python - 创建 Python 子模块

标签 python module

我想创建一个名为 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 文件。

enter image description here

然后是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 

在终端中像这样运行程序

enter image description here

另外,最好先创建一个对象元素,然后再继续。

关于python - 创建 Python 子模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58393436/

相关文章:

python - 当选项卡以空单元格开头时 read_excel

python - python 2.6 中没有 spawnl 函数吗?

Python 从线程更新 Matplotlib

php - 如何做一个PHP钩子(Hook)系统?

c - 在Linux中接管以太网数据

python - 在每个 "X"上分割一个字符串

python - 如何在zeep客户端中发送参数

python - 为什么 'module' 对象不可调用?

python - 子模块的相对导入

javascript - 如何在浏览器中使用 npm 模块?甚至可以在本地(PC)中使用它们?