优化从Python

时间:2017-06-01 20:29:44

标签: python python-2.7 csv optimization

我想使用csv模块为每个列表创建一个CSV。我的代码有效,但是一次又一次地写同样的行感觉有点傻。我想知道是否有更好,更有效的方法来编写这部分。

我的电子表格共有3张。 row1在列表中包含sheet1数据,row2在列表中包含sheet2数据,依此类推。

  with open("sheet1.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(rows1)

  with open("sheet2.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(rows2)

  with open("sheet3.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(rows3)

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

例如,

迭代元组列表。

for f,rows in [("sheet1.csv",rows1),("sheet2.csv",rows2),("sheet3.csv",rows3)]:
    with open(f, "wb") as f:
        writer = csv.writer(f)
        writer.writerows(rows)

请注意,将rowsX变量放入行列表并使用enumerateformat生成工作表名称会更简单,如果他们按照您的描述或如果无法轻易生成名称,请在两个列表中使用zip

row_list = [rows1,rows2,rows3]
name_list = ["apple.csv","banana.csv","orange.csv"]
for name,rows in zip(name_list,row_list):
    with open("sheet{}.csv".format(i), "wb") as f:
        writer = csv.writer(f)
        writer.writerows(rows)

另请注意:with open(f, "wb") as f:仅适用于python 2 csv writer。

对于python 3,请执行:with open(f, "w", newline="") as f: