【问题标题】:Missing headers in csv output file (python)csv 输出文件中缺少标题(python)
【发布时间】:2017-04-26 04:16:48
【问题描述】:

我正在尝试输出一个 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) 

不会工作。

【问题讨论】:

  • 除了这一行必须是:new_lines = [l + [str(counts[l[1]])] for l in lines],还有什么问题?它为我运行。
  • @StephenRauch 您的代码运行良好,这是另一个问题,因为您上次解决了我的问题,所以我通知您,希望您能看到问题所在。这段代码的输出给了我没有标题的数据..
  • if item not in newfile: 想做什么?
  • @StephenRauch 删除原始 csv 文件中的重复项。 (如果尚未写入新文件,则写入数据)
  • 那样不行。这将一行与文件句柄进行比较。不是文件的内容。为此,您需要读入整个文件并将新数据与旧数据进行比较或合并。

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


【解决方案1】:

这与使用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)

【讨论】:

  • 当我尝试使用 w 而不是 w+ 时,它给了我一个错误 IOError : File not open for reading,但是如果我使用 w+,我又回到了我最初的问题,数据但 csv 输出中没有标题。
猜你喜欢
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多