osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Copying a row from a range of Excel files to another


On 2019-06-26 22:14, Cecil Westerhof wrote:
> MRAB <python at 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.

Anyway, if Workbooks are closed using a method called "close", you can 
wrap them in a "closing" context manager:

     from contextlib import closing

     with closing(Workbook()) as wb_out:
         for filepath in filepathArr:
             current_row = []

             with closing(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)