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'