【问题标题】:How to print a particular column from an Avro file using python如何使用 python 从 Avro 文件中打印特定列
【发布时间】:2019-11-04 10:06:28
【问题描述】:

我有以下代码打印 avro 文件中的所有值。但是,我想打印一个特定的列 例如:

{'key1': value1 , 'key2': value2} 

我想打印 avro 中存在的“key1”的所有值。

这是我的代码

from avro.datafile import DataFileReader
from avro.io import DatumReader
reader = DataFileReader(open("abc.avro", "rb"), DatumReader())
for user in reader:
    print(user)

reader.close()

我是 Avro 和大数据方面的新手

编辑:

这是更正后的代码。感谢@Rithin

for user in reader:
print(user['key1'])

这将返回'key1'对应的所有值

【问题讨论】:

    标签: python json python-3.x avro


    【解决方案1】:

    来自docs

    DataFileReader 是一个迭代器,它返回对应于序列化项的 dicts。

    由于它只返回一个字典列表,您可以使用row['key'] 访问它们。

    将此与列表理解相结合,将产生所有行的所有值。

    例子:

    all_values = [row['key1'] for row in list(reader)]
    print(all_values)
    
    [value1]
    

    要将此结果列表保存到json,您可以:

    import json
    
    result = {'key1':all_values}
    
    with open('output.json', 'w') as json_file:
      json.dump(result, json_file)
    
    

    您可以阅读有关保存到 json here 的更多信息。


    要将此结果列表保存到csv,您可以:

    import csv
    
    with open('output.csv', 'w') as csv_file:
      writer = csv.writer(csv_file)
      writer.writerows(all_values)
    

    您可以阅读有关使用 csv 文件的更多信息here

    【讨论】:

    • 您好,感谢您的回复。我也可以将此输出转储为 JSON 或 CSV 格式吗??
    • @ChiragSharma,用写入 csv+json 的示例更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多