写入值CSV文件

时间:2014-10-29 10:38:50

标签: python csv python-2.x

我正在尝试从下面的代码中将一些输出写入csv。第一列应该包含所有有效ID,标题为“有效(括号内计数)”。第二列应包含所有无效ID的列表,并且标题为“无效(括号内计数)”。知道我是怎么做的吗?

import csv

# csv_path = r'C:\temp\data\fileA'
csv_path = r'C:\temp\data\fileA'
reader = csv.reader(open(csv_path, 'r'), dialect='excel-tab')
reader.next() # ignore heading
min_id = 1503332138
max_id = 1503632138
valid_ids = []
invalid = []
x = 0
for line in reader:
    pv = line[1]
    if id.isdigit() and int(id) >= min_id and int(id) <= max_id:
        if id not in valid_ids:
            valid_ids.append(id)
    else:
        if id not in invalid:
            invalid.append(id)
print 'Valid IDs (',len(valid_ids),')'
for valid in valid_ids:
    print valid
print 'Invalid IDs (',len(invalid),')'
for invalid in invalid:
    print invalid

1 个答案:

答案 0 :(得分:0)

# ...
# Continuing from point where you have valid_ids and invalid lists populated

data = [('Valid IDs', valid_ids), ('Invalid IDs', invalid)]

# Create header

header = []
for (label, id_list) in data:
    label_with_count = '%s (%d)' % (label, len(id_list))
    header.append(label_with_count)

# Write to CSV file

with open('path_to_output_file.csv') as out_csv_file:
    csv_writer = csv.writer(out_csv_file)

    csv_writer.writerow(header)

    for (idx, dataset) in enumerate(data):
        (label, id_list) = dataset
        for id in id_list:
            row = (idx * ['']) + [id] + ((len(data) - idx - 1) * [''])
            csv_writer.writerow(row)