2017-04-26 244 views
0

我想输出一个csv文件,但问题是,标题不见了,我试着一行一行地看着我的代码,但我不知道什么是错的我的代码..csv输出文件中缺少标题(python)

我的样本数据是: 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) 

U不幸的是,我的输出会像这样(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) 

将无法​​正常工作。

+0

除了这一行需要:'new_lines = [l + [str(counts [l [1]])]],出了什么问题?它为我运行。 –

+0

@StephenRauch您的代码运行良好,这是另一个问题,因为您上次解决了我的问题,所以我通知您希望可能会发现错误。这段代码的输出给了我无数据头的数据。 – yunaranyancat

+0

什么是'if item not in newfile:'试图做什么? –

回答

0

这是用wb+(写入字节)打开文件。因为当你以字节模式写文件时,你需要传递一个字节数组而不是字符串。

当我运行它,我得到在控制台此错误:

TypeError: a bytes-like object is required, not 'str' 

尝试改变wb+只是w,这样做的伎俩。

with open('result_id_with_total.csv', 'w') as newfile: 
    header = ['KEY ID', 'GENERAL ID' , 'TOTAL GENERAL ID'] 
    wr = csv.writer(newfile, delimiter=',', quoting = csv.QUOTE_MINIMAL) 
+0

当我尝试使用w而不是w +时,它给了我一个错误'IOError:File not open for reading',但是如果我使用w +,我回到了我最初的问题,数据但csv输出中没有标题。 – yunaranyancat