Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a file is open in Python

Tags:

python

excel

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?

like image 859
Shansal Avatar asked Jul 26 '11 06:07

Shansal


People also ask

How do I know if a file is open in Python?

The open() function is used in Python to open a file. Using the open() function is one way to check a particular file is opened or closed. If the open() function opens a previously opened file, then an IOError will be generated.

What does open () read () do in Python?

Python has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. We can specify the mode while opening a file. In mode, we specify whether we want to read r , write w or append a to the file.


2 Answers

If all you care about is the current process, an easy way is to use the file object attribute "closed"

f = open('file.py') if f.closed:   print 'file is closed' 

This will not detect if the file is open by other processes!

source: http://docs.python.org/2.4/lib/bltin-file-objects.html

like image 181
Rmhero Avatar answered Sep 24 '22 01:09

Rmhero


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 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() 
like image 21
Tim Pietzcker Avatar answered Sep 23 '22 01:09

Tim Pietzcker