创建Python子模块

2024-10-03 06:23:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个名为unifile的工具来保存和打开文件 就像这样unifile.open.yaml("file.yaml")

这是我的结构

unifile
|
├-open
|    └--__init__.py
|
└-save
     └--__init__.py

调用我的模块的代码:

import unifile
a = unifile.open.yaml("file.yaml")

打开/\uu init\uuuuuuuuuy.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总是说:

module unifile has no atribute open

2 __init__.py出错,无法打开文件

[pylint] Context manager 'open' doesn't implement enter and exit. [not-context-manager]


Tags: 文件工具pathpyimportyamlinitsave
3条回答

两个问题,两个问题

首先您应该在unifile中添加一个init文件,用这个python可以理解unifile是一个带有子包的包

其次,open是一个内置函数,您可以通过调用类open来覆盖它。更改你的类名,它应该工作

在这里添加解决你的问题,使你的项目结构像这样

unifile/__init__.py文件添加到unifile本身而不是其他模块中

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

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

  1. 出现此错误是因为unifile不是包,与open和save相同的顶层没有init.py文件。您也不能直接调用open.yml,因为open是package open中的一个类,所以您必须从open导入open,创建其实例,然后在该实例上调用iml

    从打开导入打开

    a=open().yml('file.yml')

  2. 出现此错误是因为您试图重写pythonopen中的现有关键字,您应该严格禁止这样做。因此,您应该为类设置除保留关键字以外的任何内容

相关问题 更多 >