For Loop Skips last List

时间:2018-04-12 16:01:04

标签: python for-loop xlsxwriter xlwings

我有一个for循环语句,执行时总是创建比列表少的excel。但是当使用if语句的第一部分时(xlwings,修改现有的excels它工作得很好)思考?

names= list(df_ora['XCODE'].unique())
for prov in names:
    #for each matching agency code we create a df2
    df2 = df_ora[df_ora['CODE'].isin([prov,'00000'])]
   # create a filename to verify the excel exisits
    filename = (dir_src  + '\\' + str(prov) + '_' + 'Claims' + '.xlsx')
    if os.path.isfile(filename):
        wb = xw.Book(filename)
        ws = wb.sheets['DATA']
        ws.clear_contents()
        ws.range('A1').options(index=False).value = df2
        ws.autofit()
        wb = xw.Book(filename)
        wb.save()
        xw.apps[0].quit()
        counter = counter + 1
    else:
        writer = pd.ExcelWriter(filename, engine='xlsxwriter')  
        df2.to_excel(writer, sheet_name='DATA',index=False)
        counter = counter + 1

1 个答案:

答案 0 :(得分:2)

尝试在writer.save()之后立即关闭作者或df2.to_excel(writer, sheet_name='DATA',index=False)。在明确关闭或超出范围之前,编写者的内容可能不会刷新到磁盘。