【问题标题】:Key values of CSV incorrect causing key errorCSV 的键值不正确导致键错误
【发布时间】:2019-02-02 16:07:57
【问题描述】:

我有一个 csv 文件,我试图从中提取一个特定的列,但我得到了 keyerror。当我尝试打印 csv 的键时,我得到了这个结果:

[None, 'Id;"PostTypeId";"ParentId";"AcceptedAnswerId";"OwnerUserId";"LastEditorUserId";"OwnerDisplayName";"LastEditorDisplayName";"UserIdCombined"']

我试过的代码:

    read_file = open ("ml_sample_complete.csv","r") # open input file for reading
    col_dict = {}
    with open('out.csv', 'wb') as f: # output csv file
        writer = csv.writer(f)
    with open('ml_sample_complete.csv','r') as csvfile: # input csv file
        reader = csv.DictReader(csvfile, delimiter=',')
        for row in reader:
            print(row.keys())
            print(row["Tags"])
            col_dict.update(row)
    print(col_dict)
    read_file.close()

请帮助我了解这里出了什么问题以及如何纠正它。

【问题讨论】:

  • 显示您的代码。

标签: python csv keyerror


【解决方案1】:

你确定你的定界符应该是','而不是';'在 dictreader 函数中。

【讨论】:

  • 谢谢!我错过了注意到这样一件微不足道的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-02
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
  • 2010-11-18
  • 2011-09-26
  • 2010-11-14
相关资源
最近更新 更多