Skip to content
Advertisement

Creating Python submodule

I want to create a tool called unifile for saving and opening files like this unifile.open.yaml("file.yaml").

This is my structure:

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

Code that call my module:

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

open/init.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")

1 error if I import unifile always say:

module unifile has no atribute open

2 error in __init__.py I can’t open file

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

Advertisement

Answer

here adding solution to ur problem, make your project structure like this.

add unifile/__init__.py file in the unifile itself not in other modules.

enter image description here

then unifile/open/_open.py file content

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")

content of the unifile/__init__.py file

from .open._open import Open 

in terminal run the program like this

enter image description here

Also, It is better to create a object element first then proceed ahead.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement