我想读取文件并将结果写入文件,例如报告。但我想在副标题下对项目进行分组。
例如,我有'testconfig'文件,其中包含以下内容:
group,monitor
group1,"Some item in group1 - with a hypen"
group2,"Some item in group2 - with a hypen"
group2,"Another item in group2, but with a comma"
group2,"Plain old item in group2"
group3,"The first item in group3 - with hypen"
group3,"Another item in group3, including comma"
我的代码是:
import csv
f1 = csv.DictReader(open('testconfig'))
for row in f1:
if row['group'] == 'group1':
print("Group1: " + '\n' + " " + row['monitor'])
if row['group'] == 'group2':
print("Group2: " + '\n' + " " + row['monitor'])
if row['group'] == 'group3':
print("Group3: " + '\n' + " " + row['monitor'])
我目前的输出是:
Group1:
Some item in group1 - with a hypen
Group2:
Some item in group2 - with a hypen
Group2:
Another item in group2, but with a comma
Group2:
Plain old item in group2
Group3:
The first item in group3 - with hypen
Group3:
Another item in group3, including comma
这就是我想要的:
Group1:
Some item in group1 - with a hypen
Group2:
Some item in group2 - with a hypen
Another item in group2, but with a comma
Plain old item in group2
Group3:
The first item in group3 - with hypen
Another item in group3, including comma
我理解为什么我会得到目前的结果,但还是无法弄清楚如何获得我想要的结果。我使用的是Python 2.7,如果有帮助的话。
答案 0 :(得分:3)
最简单的方法是跟踪上次打印的小组
f1 = csv.DictReader(open('testconfig'))
last_group = ''
for row in f1:
if row['group'] != last_group:
print row['group'] + ':'
last_group = row['group']
print " " + row['monitor']
答案 1 :(得分:0)
这是itertools.groupby
擅长的:
import csv
import itertools
with open('data.csv') as data:
reader = csv.reader(data)
reader.next() # skip the first line, which is a header
for group, text in itertools.groupby(reader, key=lambda x: x[0]):
print group.capitalize() + ":"
for line in text:
print "\t" + line[1]
输出:
Group1:
Some item in group1 - with a hypen
Group2:
Some item in group2 - with a hypen
Another item in group2, but with a comma
Plain old item in group2
Group3:
The first item in group3 - with hypen
Another item in group3, including comma