读取headers等N行数据

Read headers and N rows of data

我有一个函数可以接受四种类型的文件:

这些文件最多可以包含几千行数据。我想获取文件的 headers 列,以及 N 示例数据行(不需要是前 N 个,但需要是总共 N 个)。一个例子:

来自animals.csv

收件人:

animals = {
    "dogs": [1, 5, 8],
    "cats": [2, 6, 9],
    "birds": [3, 10, 14],
    "frogs": [4, 8, 11]
}

最有效的方法是什么?

测试文件:

这是我的解决方案。不过,我并不声称它是 "most efficient"。您需要安装 xlrd (pip3 install xlrd)。问题描述中提供了测试文件。


import collections
import pathlib
import csv
import json
import xlrd

file = "animals.csv"

f_sufx = pathlib.Path(file).suffix
if f_sufx == ".csv":
    with open(file, 'r') as f:
        reader = csv.DictReader(f)
        d = collections.defaultdict(set)
        for r in reader:
            for k, v in r.items():
                if len(d[k]) < 3 and v:
                    d[k].add(v)
elif f_sufx == ".json":
    with open(file, 'r') as f:
        d = collections.defaultdict(set)
        for r in json.load(f):
            for k, v in r.items():
                if len(d[k]) < 3 and v:
                    d[k].add(v)
elif f_sufx in [".xls", ".xlsx"]:
    d = collections.defaultdict(set)
    sh = xlrd.open_workbook(file).sheet_by_index(0)  
    for row in range(2, sh.nrows):
        for col in range(sh.ncols):
            if len(d[sh.cell_value(1, col)]) < 3 and sh.cell_value(row, col):
                d[sh.cell_value(1, col)].add(sh.cell_value(row, col))

print(d)