[Python] Close all files opened in python module when the module is stopped abnormally

Discussão em 'Python' iniciado por Stack, Abril 3, 2025.

  1. Stack

    Stack Membro Participativo

    In my module, one block is coded like this:

    # open a text file to which results obtained in MAINBLOCK will be written
    write2file = open('myResults.txt','w')
    # MAINBLOCK
    write2file.close()


    When running the module, I may interrupt the module in IDLE by Ctrl+C for program debugging or exceptions may be raised in MAINBLOCK, so the module is stopped abnormally. However, If I try to delete myResults.txt in Windows Explorer at the time, the message says:

    The action can't be completed because the file is open in pythonw.exe


    I think if the module is stopped abnormally, the file is still opening, am I right? How can I close all those open file identifiers in IDLE or by other ways?

    Continue reading...

Compartilhe esta Página