I have been using xlwings to edit some excel files in python, but i am having trouble for one specific file. After I am done editing it, I pass a command for python to save and close that workbook, but it closes the file before it´s done saving, I have used the following command to remediate the issue: time.sleep(2)
, but I understand that this is not very efficient, nor is it dinamic, and many times, even with that, the file closes before saving. I now that I could increase the seconds in the sleep command, but I would much rather prefer some code that waits for the save to finish for it to close.
I have looked around this website and many others and could´nt find an answer, people only mention ways for python to wait for some calculation to be complete in order for it to get some value, but they don´t mention wating for the save to close the file. My code is structured as follows:
import xlwings as xw
import time
app = xw.App()
excel = xw.Book("file path")
excel_sheet = excel.sheets("sheet name")
##This is just an example of changing something in the file
excel_sheet.range("A1").value = 123
excel.save()
time.sleep(2)
excel.close()
app.quit
Update: I have now tried using a context manager, but without success, here is my code:
import xlwings as xw
import time
app = xw.App()
with xw.Book("file path") as excel:
excel_sheet = excel.sheets("sheet name")
##This is just an example of changing something in the file
excel_sheet.range("A1").value = 123
excel.save()
app.quit