Reputation: 663
How to close a file if it is already open?
import xlwings as xw
wb = xw.Book(folderpath + 'Metrics - auto.xlsx')
Using try:except: but need a way to close the file so it can be opened, or find the file and work with it?
I get this error if it's already open:
wb = xw.Book(folderpath + 'Metrics - auto.xlsx')
Traceback (most recent call last):
File "<ipython-input-34-85b6fd35627b>", line 1, in <module>
wb = xw.Book(folderpath + 'Metrics - auto.xlsx')
File "C:\Users\ReDimLearning\AppData\Local\Continuum\anaconda2\lib\site-packages\xlwings\main.py", line 480, in __init__
impl = app.books.open(fullname).impl
File "C:\Users\ReDimLearning\AppData\Local\Continuum\anaconda2\lib\site-packages\xlwings\main.py", line 2751, in open
"Cannot open two workbooks named '%s', even if they are saved in different locations." % name
ValueError: Cannot open two workbooks named 'metrics - auto.xlsx', even if they are saved in different locations.
Upvotes: 5
Views: 5155
Reputation: 7070
You can check the workbook collection with
import xlwings as xw
xw.books
and check if your fullname is already open using something like:
if myworkbook in [i.fullname for i in xw.books]:
...
Upvotes: 5
Reputation: 4465
I have no experience with the xlwings package, but looking at the source code for Book.__init__
, it looks like it automatically looks for any instances of the work book that are already open. If there is only one, then it returns it. If there is more than one instance of the work book open, it will raise an error. If there aren't already any open instances, then it will "connect" to it. So, it looks like you don't have to worry about closing the file.
This lines up with the documentation which says:
The easiest way to connect to a book is offered by xw.Book: it looks for the book in all app instances and returns an error, should the same book be open in multiple instances.
However, after connecting to a workbook, if you really want to close it, there is a Book.close method which:
Closes the book without saving it.
Upvotes: 1