Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a process (file) if it was opened by an external program, using Python?

I am writing to a file from python, if the file is open in some process, python throws error. To make it clear, I am writing to a excel file, I want it closed if already open.

This is below code I use to write to file -

writer = pd.ExcelWriter('file_Output.xlsx', engine='xlsxwriter')
file.to_excel(writer,index=False, sheet_name='Sheet1')

Which throws below error if the file - file_Output.xlsx is already open in excel.

Traceback (most recent call last):
  File "pythonclose.py", line 311, in <module>
    writer.save()
  File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\excel.py", line 1952, in save
    return self.book.close()
  File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\site-packages\xlsxwriter\workbook.py", line 306, in close
    self._store_workbook()
  File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\site-packages\xlsxwriter\workbook.py", line 655, in _store_workbook
    allowZip64=self.allow_zip64)
  File "C:\Users\Abhinav\AppData\Local\Programs\Python\Python36\lib\zipfile.py", line 1082, in __init__
    self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'file_Output.xlsx'
like image 427
Abhinav Kumar Avatar asked Nov 25 '25 00:11

Abhinav Kumar


1 Answers

If a file is open by an external program(such as MS Excel in this case), the file handle or control of the file is with the program. Python has no control over the file and cannot close/edit it. However, if you have the Process ID for the file, it is possible to kill the process by different means(for eg. using taskkill in Windows or even with Python).

like image 106
amanb Avatar answered Nov 27 '25 14:11

amanb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!