Shansal Shansal - 2 years ago 892
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.

Answer Source

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:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download