如何在python中使用“with open”自动保存在不同的xls中?

时间:2018-05-26 07:40:37

标签: excel python-3.x

我想在with open循环中使用for在不同的Excel工作表中保存一些数据。

E.g。在i=1,2,3,4时,我想保存以下Excel表格:1.xls, 2.xls, 3.xls, 4.xls

这是我的代码:

for num in (1,2,3,4):       
    with open(r'C:\Users\Batman\Desktop\num.csv','a',encoding='ANSI') as f:
    f.close()

显然,通过这种方式,我在目标目录中只有一个xls,num.csv

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您需要将数字插入文件名中。 num.csv只是一个文字,而不是插值

此外,当您要求XLS时,请更改文件扩展名

for num in range(1,5):  # Exclusive range       
    with open(r'C:\Users\Batman\Desktop\{0}.xls'.format(num),'a',encoding='ANSI') as f:
        pass
以这种方式打开文件时不需要

f.close()