Shansal Shansal - 11 months ago 690
Python Question

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 writing process. Could you supply me with some python code to do this task?

Thanks in advance.


I assume that you're writing to the file, then close 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 should do that:

    myfile = open("myfile.csv", "r+") # or "a+", whatever you need
except IOError:
    print "Could not open file! Please close Excel!"

with myfile: