csv输出文件中缺少标题(python)

时间:2017-04-26 04:16:48

标签: python csv python-2.x standard-library

我正在尝试输出一个csv文件,但问题是,标题已经消失,我尝试逐行查看我的代码,但我不知道我的代码有什么问题..

我的示例数据是: ABC.csv(假设其中有多个数据,所以我还添加了如何删除它的代码)

KeyID,GeneralID
145258,KL456
145259,BG486
145260,HJ789
145261,KL456
145259,BG486
145259,BG486

我的代码:

import csv
import fileinput
from collections import Counter

file_path_1 = "ABC.csv"

key_id = []
general_id = []
total_general_id = []

with open(file_path_1, 'rU') as f:
    reader = csv.reader(f)
    header = next(reader)
    lines = [line for line in reader]
    counts = Counter([l[1] for l in lines])


new_lines = [l + [str(counts[l[1])] for l in lines]
with open(file_path_1, 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(header + ['Total_GeneralID'])
    writer.writerows(new_lines)

with open(file_path_1, 'rU') as f:
    reader = csv.DictReader(f)
    for row in reader:
        key_id.append(row['KeyID'])
        general_id.append(row['GeneralID'])
        total_general_id.append(['Total_GeneralID'])

New_List = [[] for _ in range(len(key_id))]
for attr in range(len(key_id)):
    New_List[attr].append(key_id[attr])
    New_List[attr].append(general_id[attr])
    New_List[attr].append(total_general_id[attr])

with open('result_id_with_total.csv', 'wb+') as newfile:
    header = ['KEY ID', 'GENERAL ID' , 'TOTAL GENERAL ID']
    wr = csv.writer(newfile, delimiter=',', quoting = csv.QUOTE_MINIMAL)
    wr.writerow(header) #I already add the headers but it won't work. 
    for item in New_List:
        if item not in newfile:
            wr.writerow(item)

不幸的是,我的输出将是这样的(result_id_with_total.csv);

145258,KL456,2
145259,BG486,1
145260,HJ789,1
145261,KL456,2

我想要实现的目标;

KEY ID,GENERAL ID,TOTAL GENERAL ID 
145258,KL456,2
145259,BG486,1
145260,HJ789,1
145261,KL456,2

我在此代码中的主要问题:

wr.writerow(header) 

无效。

1 个答案:

答案 0 :(得分:0)

这与打开import com.itextpdf.layout.element.Paragraph (写入字节)的文件有关。因为当你以字节模式写一个文件时,你需要传递一个字节数组而不是字符串。

运行时,我在控制台中收到此错误:

wb+

尝试将TypeError: a bytes-like object is required, not 'str' 更改为wb+,这样就可以了。

w