Search code examples
pythonexcel

check if a file is open in Python


In my app, I write to an excel file. After writing, the user is able to view the file by opening it. But if the user forgets to close the file before any further writing, a warning message should appear. So I need a way to check this file is open before the writing process. Could you supply me with some python code to do this task?


Solution

  • I assume that you're writing to the file, then closing it (so the user can open it in Excel), and then, before re-opening it for append/write operations, you want to check that the file isn't still open in Excel?

    This is how you could do that:

    while True:   # repeat until the try statement succeeds
        try:
            myfile = open("myfile.csv", "r+") # or "a+", whatever you need
            break                             # exit the loop
        except IOError:
            input("Could not open file! Please close Excel. Press Enter to retry.")
            # restart the loop
    
    with myfile:
        do_stuff()