【问题标题】:How to wrtie the for loop out put to a csv file?如何将 for 循环输出写入 csv 文件?
【发布时间】:2020-08-08 12:24:15
【问题描述】:

我有一个function,它返回一个list ..

def give_list(number, type, index): 
        list_ = []
        do something 
    return list_

这个函数的输出格式如下;

['Training/1.png', 3450, 3865, 1517, 1789, 'GOOD']

现在我使用 for 循环来获取更多类似上面的列表并写入 .csv 文件..

for key, value in dic_.items():
    list_ = give_list(key, "CC", 2)
    df = pd.DataFrame(list_)
    df.to_csv('/path/to/write/testFile.csv', sep=',') 

例如我的循环生成以下输出;

['Training/1.png', 1255, 4556, 1455, 1789, 'GOOD']
['Training/2.png', 4555, 2899, 6989, 1586, 'BAD']
['Training/3.png', 4744, 2478, 9862, 1755, 'BAD']
['Training/4.png', 3450, 6989, 2455, 3866, 'GOOD']

我在 for 循环中的 df.to_csv('/path/to/write/testFile.csv', sep=',') 并不能帮助我将输出写入 .csv 文件中。我怎样才能做到这一点? 我需要在.csv 文件中看到这样的输出;

'Training/1.png', 1255, 4556, 1455, 1789, 'GOOD'
'Training/2.png', 4555, 2899, 6989, 1586, 'BAD'
'Training/3.png', 4744, 2478, 9862, 1755, 'BAD'
'Training/4.png', 3450, 6989, 2455, 3866, 'GOOD'

【问题讨论】:

  • 你为什么不直接做pd.DataFrame(dict_).to_csv('/path/to/file/)

标签: python python-3.x pandas list csv


【解决方案1】:

试试这个:

import csv 
payload = [give_list(key, "CC", 2) for key in dic_] # create list of lists(rows) payload
with open('/path/to/write/testFile.csv', "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(payload)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2021-05-13
    • 2019-07-20
    • 2014-07-29
    • 2017-08-26
    • 2018-01-12
    • 1970-01-01
    相关资源
    最近更新 更多