如何将多行打印输出转为CSV列标题并批量存储多组数据?
Got it, let's tackle this problem. You need to take multiple sets of values (like your two groups: First/Random/Degree/Largest and Second/Odd/Inclined/Maximum) and write them into a CSV file with fixed column headers: Group, Number, Angle, Max value.
Method 1: Using Python's Built-in csv Module
This is perfect if you want to stick to standard libraries without installing extra packages.
First, store all your data groups in a list (each group is a sub-list matching the order of your headers). Then use the csv.writer to write headers and rows to a file:
import csv # Define your column headers headers = ['Group', 'Number', 'Angle', 'Max value'] # Store all your data groups here (add as many as you need) data_groups = [ ['First', 'Random', 'Degree', 'Largest'], ['Second', 'Odd', 'Inclined', 'Maximum'], # Example of a third group to extend: # ['Third', 'Even', 'Straight', 'Minimum'] ] # Write to CSV file with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile: # Create a CSV writer object writer = csv.writer(csvfile) # Write the header row first writer.writerow(headers) # Write all data groups in one go writer.writerows(data_groups)
Method 2: Using pandas (Simpler for Larger Datasets)
If you're working with more data or want a more concise approach, pandas is a great tool. Install it first if you haven't (pip install pandas), then use this code:
import pandas as pd # Define your data as a list of dictionaries (each dict maps header to its value) data = [ {'Group': 'First', 'Number': 'Random', 'Angle': 'Degree', 'Max value': 'Largest'}, {'Group': 'Second', 'Number': 'Odd', 'Angle': 'Inclined', 'Max value': 'Maximum'} ] # Create a DataFrame from the data df = pd.DataFrame(data) # Write to CSV (set index=False to avoid adding an extra index column) df.to_csv('output_pandas.csv', index=False, encoding='utf-8')
Sample Output CSV Content
Both methods will generate a CSV file with content like this:
Group,Number,Angle,Max value First,Random,Degree,Largest Second,Odd,Inclined,Maximum
No matter how many groups N you have, just add them to the data_groups (for csv module) or data (for pandas) list, and the code will handle writing all rows correctly.
内容的提问来源于stack exchange,提问作者axay

