如何使用 python 从 Avro 文件打印特定列
How to print a particular column from an Avro file using python
我有以下代码打印 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'])
这将return对应于'key1'
的所有值
来自docs:
The DataFileReader is an iterator that returns dicts corresponding to the serialized items.
因为它只是 returns 一个词典列表,您可以使用 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。
我有以下代码打印 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'])
这将return对应于'key1'
的所有值来自docs:
The DataFileReader is an iterator that returns dicts corresponding to the serialized items.
因为它只是 returns 一个词典列表,您可以使用 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。