将List输出为.csv文件

时间:2018-05-12 11:28:51

标签: python list csv export

我写了一个程序来删除一些特殊的单词,数字 并将输出存储在列表c中,但我不知道如何将输出(即列表c)导出到python中的.csv文件

with open('stat_memory_cpu.txt', 'r') as f:
  reader = csv.reader(f)
  your_list = list(reader)
b = []
c = []
for i in range(1,5):
    b = your_list[i][0]
    b = b.replace('180510 ', '')
    d.append(b)
    c = b +","+your_list[i][1]+","+your_list[i][2]
    print(c)

Input 
=====
Data
180510 00:00,10.4,1.56
180510 00:01,10.4,2.33
180510 00:02,10.4,6.00
180510 00:03,10.4,4.03
Output 
======
00:00,10.4,1.56
00:01,10.4,2.33
00:02,10.4,6.00
00:03,10.4,4.03

2 个答案:

答案 0 :(得分:0)

您可以通过打开具有写入权限的新文件将其写入新文件中。

with open('stat_memory_cpu.txt', 'r') as f:
  reader = csv.reader(f)
  your_list = list(reader)

with open('result.csv', 'w') as csvfile:   
    writer = csv.writer(csvfile)

    b = []
    c = []
    for i in range(1,5):
        b = your_list[i][0]
        b = b.replace('180510 ', '')
        d.append(b)
        c = b +","+your_list[i][1]+","+your_list[i][2]
        print(c)
        writer.writerow(x)

答案 1 :(得分:0)

您可以使用csv.writer每次写一整行,在这种情况下使用您的元素创建一个列表。并使用来自csv.writer的方法writerow。首先你导入模块csv,然后构造一个对象编写器对象,在csv中你想要的方言就像引用char,分隔符char一样,你可以通过这个对象将列表传递给它,他会自动编写在你的文件上划一行。文档中的示例如下所示。

    import csv
    with open('eggs.csv', 'w', newline='') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
        spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
  

https://docs.python.org/3/library/csv.html#csv.writer