如何将含115个邮箱的列表按每10个拆分写入多个CSV文件?
Solution to Split Email List into Multiple CSV Files
Got it, let's tackle this problem together! You want to split your my_network_emails list (with 115 emails) into chunks of 10, then write each chunk to a sequentially numbered CSV file like network_csv_01.csv, network_csv_02.csv, etc. Here's a clean, efficient way to do it:
Complete Code
import csv # Replace this with your actual 115-emails list my_network_emails = ["email1@example.com", "email2@example.com", ...] # Iterate over the list in chunks of 10 for i in range(0, len(my_network_emails), 10): # Calculate file number and format as two-digit string for consistent naming file_number = i // 10 + 1 filename = f"network_csv_{file_number:02d}.csv" # Grab the current chunk of up to 10 emails email_chunk = my_network_emails[i:i+10] # Write the chunk to the corresponding CSV file with open(filename, 'w', newline='') as f: writer = csv.writer(f) for email in email_chunk: writer.writerow([email])
Key Explanations
- Chunking the list: The
range(0, len(my_network_emails), 10)generates starting indices for each chunk (0, 10, 20, ...). The slicemy_network_emails[i:i+10]grabs up to 10 emails each time—even the final chunk (which will have 5 emails for your 115-item list) is handled smoothly, since Python slicing automatically stops at the end of the list. - Sequential filenames: Using
file_number:02din the f-string ensures the file number is always two digits (e.g.,01instead of1), keeping your filenames consistent and sorted correctly in file explorers. - CSV writing best practice: Adding
newline=''to theopen()call prevents extra blank lines from being written in CSV files on Windows systems—this is a common gotcha that's easy to fix.
Quick Notes
- Don't forget to import the
csvmodule (it's part of Python's standard library, so no extra installation is needed). - If the target CSV files already exist, this code will overwrite them. If you need to append instead, change
'w'to'a'in theopen()call—but that's probably not necessary for fresh splits.
内容的提问来源于stack exchange,提问作者rachidj
相关产品推荐
相关产品推荐

