You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python中for循环的输出内容导出为CSV文件?

实现方法

你可以根据对CSV格式的需求,选择以下任意方案:


方案1:直接导出当前打印内容为CSV

如果不需要结构化CSV,仅需要把当前打印的 combo: xx, xx格式内容逐行存入CSV,直接修改原有代码写入文件即可:

fruits = 'apple', 'banana', 'kiwi'
veggies = 'corn','lettuce', 'spinach'

# 以写入模式打开CSV文件
with open('output.csv', 'w', encoding='utf-8') as f:
    for x, y in zip(fruits,veggies):
        content = f' combo: {x}, {y}\n'
        f.write(content)
        # 需要保留控制台打印可加下一行
        # print(content.rstrip('\n'))

方案2:生成标准结构化CSV文件

如果需要生成可被Excel、Numbers等表格工具正常识别的结构化CSV,推荐使用Python自带的csv标准库,避免特殊字符导致的格式错乱:

import csv

fruits = 'apple', 'banana', 'kiwi'
veggies = 'corn','lettuce', 'spinach'

# newline参数可避免Windows系统下出现多余空行
with open('standard_output.csv', 'w', encoding='utf-8', newline='') as csv_file:
    writer = csv.writer(csv_file)
    # 可选:写入表头
    writer.writerow(['组合内容'])
    # 逐行写入数据
    for x, y in zip(fruits, veggies):
        writer.writerow([f'combo: {x}, {y}'])

如果需要把水果和蔬菜拆分两列存储,调整写入逻辑即可:

import csv

fruits = 'apple', 'banana', 'kiwi'
veggies = 'corn','lettuce', 'spinach'

with open('split_output.csv', 'w', encoding='utf-8', newline='') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(['水果', '蔬菜'])
    for x, y in zip(fruits, veggies):
        writer.writerow([x, y])

内容的提问来源于stack exchange,提问作者jarvis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:24:02