[Python] Does file_obj.close() nicely close file objects in other modules that have been set...

Discussão em 'Python' iniciado por Stack, Maio 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have a file main_file.py that creates a global variable file_obj by opening a text file and imports a module imported_module.py which has functions that write to this file and therefore also has a global variable file_obj which I set equal to file_obj in main_file.py:

    main_file.py

    import imported_module as im
    file_obj = open('text_file.txt', mode='w')
    im.file_obj = file_obj

    def main():
    a = 5
    b = 7
    im.add_func(a, b)
    im.multiply_func(a, b)
    return

    def add_func(x, y):
    z = x + y
    file_obj.write(str(z) + '\n')
    return

    main()
    file_obj.close()


    imported_module.py

    file_obj = None

    def multiply_func(x, y):
    z = x * y
    file_obj.write(str(z) + '\n')
    return


    If I close file_obj in main_file.py as above, does this also nicely close file_obj in imported_module.py?

    (In the MRE above, I could add im.file_obj.close() to main_file.py just to be sure. However, a generalization of this explicit approach does not appear possible if imported_module.py imports a second module imported_module0.py which also has a global variable file_obj and sets this variable to its own copy of file_obj with a command like im0.file_obj = file_obj.)

    Continue reading...

Compartilhe esta Página