如何将for循环写到csv文件中?

时间:2020-04-24 20:11:50

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

我有一个i = 77 character: M i = 128567 character: ? Hit. i = 110 character: n i = 100 character: d i = 97 character: a i = 121 character: y i = 84 character: T i = 117 character: u i = 101 character: e i = 115 character: s i = 100 character: d i = 128567 character: ? Hit. i = 121 character: y i = 87 character: W i = 101 character: e i = 100 character: d i = 110 character: n i = 101 character: e i = 115 character: s i = 100 character: d i = 97 character: a i = 121 character: y count = 2 userCharacter.codePointAt( 0 ): 128567 返回了一个function ..

list

此函数的输出采用以下格式;

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

现在,我使用for循环来获取更多类似上述的列表,并将其写入['Training/1.png', 3450, 3865, 1517, 1789, 'GOOD'] 文件中。.

.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

1 个答案:

答案 0 :(得分:2)

尝试一下:

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)