如何用Python生成销售订单CSV对应的指定格式Payload?
Hey there! Let's figure out how to generate that custom payload from your CSV file using Python. Here's a step-by-step solution that matches exactly what you need:
Step 1: Import Required Tools
We'll use Python's built-in csv module to read the file, and defaultdict from the collections module to group rows by SNo and Customer_id easily.
import csv from collections import defaultdict
Step 2: Read and Group CSV Data
First, we'll read the CSV file and group all rows that share the same SNo and Customer_id together. This helps us combine multiple line items under the same order header.
# Initialize a dictionary to group orders: key = (SNo, Customer_id), value = list of line items order_groups = defaultdict(list) with open('销售订单.csv', 'r', encoding='utf-8') as csv_file: # Use DictReader to access columns by their header names reader = csv.DictReader(csv_file) for row in reader: # Clean up whitespace from each field (your CSV has extra spaces in cells) sno = row['SNo'].strip() customer_id = row['Customer_id'].strip() # Collect the line item details line_item = { 'Itemid': row['Itemid'].strip(), 'Product': row['Product'].strip(), 'Quanity': row['Quanity'].strip(), 'Price\']': row["Price']"].strip() # Match the exact header name from your CSV } # Add the line item to its corresponding order group order_groups[(sno, customer_id)].append(line_item)
Step 3: Generate the Custom Payload
Now we'll iterate over each order group and build the payload string following your specified format. We'll combine the header fields first, then append all line items for that order.
payload_lines = [] for (sno, customer_id), line_items in order_groups.items(): # Build the header part of the payload header_section = f"<SNo{sno} </SNo><Customer_id{customer_id} </Customer_id>" # Build the line items section items_section = [] for item in line_items: item_str = ( f" <Itemid{item['Itemid']} </Itemid>" f" <Product{item['Product']} </Product>" f" <Quanity{item['Quanity']} </Quanity>" f" <Price']{item['Price']']}</Price']>" ) items_section.append(item_str) # Combine header and items into one line for the order full_order_payload = header_section + ''.join(items_section) payload_lines.append(full_order_payload) # Join all order payloads into the final result (each order on a new line) final_payload = '\n'.join(payload_lines) # Print or save the result print(final_payload)
What This Does
- Grouping: Uses
defaultdictto automatically organize rows bySNoandCustomer_id, so all line items for the same order stay together. - Whitespace Cleanup: The
.strip()method removes extra spaces from your CSV cells (like"1 "or" ABC123 "). - Exact Format Matching: Builds the payload string exactly as you specified, with tags like
<Itemid10 </Itemid>and<Price']10001</Price']>.
When you run this code with your sample CSV, it will output:
<SNo1 </SNo><Customer_idABC123 </Customer_id> <Itemid10 </Itemid> <ProductX1 </Product> <Quanity1001 </Quanity> <Price']10001</Price']> <Itemid20 </Itemid> <ProductX2 </Product> <Quanity1002 </Quanity> <Price']10002</Price']> <SNo2 </SNo><Customer_idCBC321 </Customer_id> <Itemid10 </Itemid> <ProductX5 </Product> <Quanity1005 </Quanity> <Price']10005</Price']> <Itemid20 </Itemid> <ProductX6 </Product> <Quanity1006 </Quanity> <Price']10006</Price']>
内容的提问来源于stack exchange,提问作者Karthi

