check if a file is open in Python

PythonExcel

Python Problem Overview


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?

Python Solutions


Solution 1 - 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

Solution 2 - Python

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()

Solution 3 - 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.')

Solution 4 - Python

You could use with open("path") as file: so that it automatically closes, else if it's open in another process you can maybe try as in Tims example you should use except IOError to not ignore any other problem with your code :)

try:
   with open("path", "r") as file: # or just open
       # Code here
except IOError:
   # raise error or print

Solution 5 - Python

Using

try:
with open("path", "r") as file:#or just open

may cause some troubles when file is opened by some other processes (i.e. user opened it manually). You can solve your poblem using win32com library. Below code checks if any excel files are opened and if none of them matches the name of your particular one, openes a new one.

import win32com.client as win32
xl = win32.gencache.EnsureDispatch('Excel.Application')

my_workbook = "wb_name.xls"
xlPath="my_wb_path//" + my_workbook


if xl.Workbooks.Count > 0:
    # if none of opened workbooks matches the name, openes my_workbook 
    if not any(i.Name == my_workbook for i in xl.Workbooks): 
        xl.Workbooks.Open(Filename=xlPath)
        xl.Visible = True
#no workbooks found, opening
else:  
    xl.Workbooks.Open(Filename=xlPath)
    xl.Visible = True

'xl.Visible = True is not necessary, used just for convenience'

Hope this will help

Solution 6 - Python

Try this method if the above methods corrupt your excel file.

This function attempts to rename the file with its own name. If the file has already been opened, the edit will be reject by the os and an OSError exception will be raised. It does not touch the inner code so it will not corrupt your excel files. LMK if it worked for you.

def check_file_status(self):
try:
    os.rename("file1.xlsx", "file1.xlsx")
    print("File is closed.")
except OSError:
    print("File is opened.")

Solution 7 - Python

if myfile.closed == False:
   print("File is still open ################")

Solution 8 - Python

Just use this function. It will close any already opened excel file

import os

def close():

    try:
        os.system('TASKKILL /F /IM excel.exe')

    except Exception:
        print("KU")

close()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShansalView Question on Stackoverflow
Solution 1 - PythonRmheroView Answer on Stackoverflow
Solution 2 - PythonTim PietzckerView Answer on Stackoverflow
Solution 3 - PythonDoubleDView Answer on Stackoverflow
Solution 4 - PythonthabubbleView Answer on Stackoverflow
Solution 5 - PythonjabbaView Answer on Stackoverflow
Solution 6 - Pythonhungry_ghost_123View Answer on Stackoverflow
Solution 7 - PythonDexterView Answer on Stackoverflow
Solution 8 - PythonADITYA JYOTIView Answer on Stackoverflow