在python中为csv添加新行以打印列输出

时间:2017-05-12 03:36:21

标签: python csv

我对python很新,我正在尝试确定最佳方法。我有以下代码。

import csv
from collections import defaultdict
columns = defaultdict(list)

with open('test.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
    for (k,v) in row.items():
        columns[k].append(v)

print(columns['Created'])
print(columns['Person'])
print(columns['Comment'])

我正在针对以下CSV文件输出运行它。

Created,UnwantedData,Person,Bogus,Comment
4-15-17,test,Chad,w,There is an update
4-16-17,for,Marlon,x,There is no update
4-17-17,this ,Kevin,y,I have reviewed the files
4-18-17,issue,Dan,z,I hate this place.

我只想打印Created,Person和Comment部分,但是我会得到以下内容。

['4-15-17', '4-16-17', '4-17-17', '4-18-17']
['Chad', 'Marlon', 'Kevin', 'Dan']]
['There is an update ', 'There is no update', 'I have reviewed the files ', 'I hate this place. ']

我试图通过在每次打印输出之间添加一个新行来使输出看起来像这样。

4-15-17   
Chad   
There is an update     

4-16-17
Marlon
There is no update

4-17-17
Kevin
I have reviewed the files

4-18-17 
Dan
I hate this place.

任何事情都会受到高度赞赏

2 个答案:

答案 0 :(得分:1)

我可以建议一种替代方法,只需创建一个新的dict条目列表,只需将其过滤为仅包含所需的密钥。

import csv
wanted = ('Created', 'Person', 'Comment')

with open('test.csv') as f:
    rdr = csv.DictReader(f)

    result = []
    for row in rdr:
        result.append({k: v for k, v in row.items() if k in wanted})

for r in result:
    print(r['Created'])
    print(r['Person'])
    print(r['Comment'])
    print('')

如果您希望使用现有代码,只需使用zip重新加入每个列表中的项目。

import csv
from collections import defaultdict
columns = defaultdict(list)

with open('test.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        for k, v in row.items():
            columns[k].append(v)

params = [columns['Created'], columns['Person'], columns['Comment']]
for cre, pers, cmt in zip(*params):
    print(cre)
    print(pers)
    print(cmt)
    print('')

答案 1 :(得分:0)

可以在单次迭代中实现结果。它会节省时间。

import csv
from collections import defaultdict

with open('test.csv') as f:
    reader = csv.DictReader(f)
    for row_dict in reader:
        print "%s\n%s\n\n" % (row_dict['Created'], row_dict["Person"], row_dict['Comment'])