【问题标题】:Python - CSV reader - unable to read all linesPython - CSV 阅读器 - 无法读取所有行
【发布时间】:2018-02-01 05:29:59
【问题描述】:

我有以下sn-p

import csv

data = {}
with open('data.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, quotechar=None)
    count = 0
    for row in spamreader:
        data.update({row[0]:row[1]})
        count+=1
        

print(count)
print(len(data))

文件data.csv共包含234611行2列。

输出是:

234611

52183

现在阅读器可以阅读所有行,但无法将它们填充到data 字典中。知道如何调试此问题吗? 另外值得一提的是,csv 文件中包含很多非英文字符。

【问题讨论】:

    标签: python csv reader


    【解决方案1】:

    字典丢弃(或更确切地说是重写)重复键的值。您确定 csv 文件中没有重复的条目吗?

    如果您想收集给定键的所有值,请使用defaultdict(list)

    import csv
    from collections import defaultdict
    
    data = defaultdict(list)
    with open('data.csv', 'rb') as csvfile:
        spamreader = csv.reader(csvfile, quotechar=None)
        count = 0
        for row in spamreader:
            data[row[0]].append(row[1])
            count+=1
    
    
    print(count)
    print(len(data))
    

    【讨论】:

    • 哦,是的,有一些重复的条目。完全忘记了这一点。非常感谢! :)
    【解决方案2】:

    您可能正在向字典中添加重复键 (row[0])。您可以使用count 或将count 附加到row[0] 来确保密钥是唯一的。

    【讨论】:

      猜你喜欢
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多