简体   繁体   中英

Optimize writing multiple CSV files from lists in Python

I want to create one CSV per list using csv module. My code works but it feels a little silly writing the same lines again and again. I was wondering if there is a better, efficient way to code this part.

My spreadsheet has a total of 3 sheets. row1 has the sheet1 data in a list, row2 has the sheet2 data in a list and so on.

  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)

Any help would be appreciated. Thank you!

iterate on a list of tuples for instance.

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)

note that it would be even simpler to put your rowsX variables in a list of rows and generate sheet names using enumerate and format if they're as you described or use zip on both lists if names cannot be easily generated.

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)

also note: with open(f, "wb") as f: is only for python 2 csv writer.

For python 3, do: with open(f, "w", newline="") as f:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM