MRAB <pyt...@mrabarnett.plus.com> writes: > On 2019-06-26 22:14, Cecil Westerhof wrote: >> MRAB <pyt...@mrabarnett.plus.com> writes: >> >>> Does Workbook support the 'with' statement? >>> >>> If it does, then that's the best way of doing it. >>> >>> (Untested) >>> >>> with Workbook() as wb_out: >>> for filepath in filepathArr: >>> current_row = [] >>> >>> with load_workbook(filepath) as wb_in: >>> for cell in wb_in.active[src_row]: >>> current_row.append(cell.value) >>> >>> wb_out.active.append(current_row) >>> >>> wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') + >>> report_end) >> >> It seems not. I get AttributeError. >> > You didn't say which line.
I made a minimalist program to show it: #!/usr/bin/env python3 from openpyxl import Workbook with Workbook() as wb_out: print('In loop') print('After loop') This results in: Traceback (most recent call last): File "./test.py", line 7, in <module> with Workbook() as wb_out: AttributeError: __exit__ > Anyway, if Workbooks are closed using a method called "close", you can > wrap them in a "closing" context manager: That seems to work. I changed it to: #!/usr/bin/env python3 from contextlib import closing from datetime import datetime from openpyxl import Workbook with closing(Workbook()) as wb_out: print('In loop') wb_out.save('testing_' + datetime.now().strftime('%Y-%m-%d') + '.xlsx') print('After loop') And I see: In loop After loop And a testing Excel file. Thanks. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list