Python实现CSV多字段条目全配对及指定格式文本生成
Solution to Generate All Breakfast-Person Pairs from CSV
Here's a straightforward Python script that reads your CSV file, creates every possible pairing between breakfast items and people, and outputs them exactly in the format you need:
import csv from itertools import product # Initialize lists to store our data breakfast_items = [] people = [] # Read the input CSV file with open('input.csv', 'r') as csv_file: # Use DictReader to access columns by their named headers reader = csv.DictReader(csv_file) for row in reader: # Clean up values and add to respective lists (skip empty entries) item = row['col1'].strip() if item: breakfast_items.append(item) person = row['col2'].strip() if person: people.append(person) # Generate all pairs and write to the output text file with open('output.txt', 'w') as output_file: # Use enumerate to get sequential numbering starting at 1 for entry_num, (item, person) in enumerate(product(breakfast_items, people), start=1): # Format each line to match your requested structure output_line = f"breakfast_{entry_num} breakfast_item {item} person {person}" output_file.write(output_line + '\n')
How This Works:
- Reading the CSV: We use
csv.DictReaderto easily pull values from thecol1(breakfast items) andcol2(people) columns. We strip any extra whitespace from each entry and skip blanks to avoid invalid pairs. - Creating All Pairs: The
itertools.productfunction handles the Cartesian product of the two lists—this means every breakfast item gets paired with every person, no matter how many entries are in each column. Perfect for when your column lengths don't match! - Writing Output: We loop through each pair with an incrementing number (starting at 1), format each line to your exact specification, and write it to a text file.
Quick Tips:
- Swap
'input.csv'with the actual file path of your CSV. - Change
'output.txt'to your preferred output file name or path. - If one column is completely empty, the output file will be blank (since there are no valid pairs to generate).
内容的提问来源于stack exchange,提问作者thinguy
相关产品推荐
相关产品推荐

