Y
Y
Yuri Anisimov2022-01-13 14:12:19
Python
Yuri Anisimov, 2022-01-13 14:12:19

Will the excel file be closed when opened through the context manager and further work of the class?

I just understand classes, I work with an Excel file, I will have to open it and parse it many times (there will be other files). I work with openpyxl. Wrote the context of the manager in order to open and close through load_workbook. In general, the level of understanding of what is happening is like that of an ancient person with a club, I poke into everything I can - it works, it's cool, no - I poke further)) 00
Below I present the context of the manager

class load_workbook_ctx_mgr(object):
    """
    Класс для открытия и закрытия Excel-файлов
    """
    def __init__(self, xl_name) ->None:
        """
        Функция для приему Excel - файла
        :param xl_name: имя Excel - файла
        """
        self.arg = xl_name


    def __enter__(self) :
        """
        Функия для открытия Excel-файл
        """
        self.wb = load_workbook(self.arg, data_only=True)
        return self.wb

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Функция для закрытия Excel-файла
        :param exc_type:
        :param exc_val:
        :param exc_tb:
        :return:
        """
        self.wb.close()


So after that I create another class that will already run through the files and do something.

class Create_List(object):
    """
    Класс для разделения Excel - файла на листы
    """
    def __init__(self, xl_name: str):
        """
        :param xl_name: имя Excel-файла
        """
        with load_workbook_ctx_mgr(xl_name) as workbook:
            self.workbook = workbook


Tell me, will he close the Excel like that? And I don't quite understand

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Anisimov, 2022-01-13
@yuriy1340

Does not save, checked by changing the class of the context manager from closing the file to saving -_-

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question