简体   繁体   中英

Write from list to csv file, 10 by 10

with open('network_csv_01.csv', 'w') as f:
    writer = csv.writer(f)
    for email in my_network_emails:
        writer.writerow([email])

I want to write csv files that contains 10 elements from a list of 115 emails, and anotherfile 02 with 10 elements and so on

Someone can help me please Thank you very much

Step 1: split the list of 115 emails into 12 lists containing 10 emails (the last one will contain only 5).

Step 2: Iterate through the list of list and write it into csv.

def chunks(l, n):
    """Splits a list into n number of lists inside a list."""
    n = max(1, n)
    return [l[i:i+n] for i in range(0, len(l), n)]

email_list = chunks(list_of_115_emails, 10) #returns a list of list,
i = 1
for emails in email_list:
    with open(f'network_csv_{i}.csv', 'w') as f:
        writer = csv.writer(f)
        for email in emails:
            writer.writerow([email])
    i += 1

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