excel – check if a file is open in Python

excel – check if a file is open in Python

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

I assume that youre 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 isnt 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()

excel – check if a file is open in Python

None of the other provided examples would work for me when dealing with this specific issue with excel on windows 10. The only other option I could think of was to try and rename the file or directory containing the file temporarily, then rename it back.

import os

try: 
    os.rename(file.xls, tempfile.xls)
    os.rename(tempfile.xls, file.xls)
except OSError:
    print(File is still open.)

Leave a Reply

Your email address will not be published. Required fields are marked *