python3 讀取avro文件

官網示例文檔:http://avro.apache.org/docs/current/gettingstartedpython.html#download_installhtml

須要注意的是,官網給出的是py2.x的示例代碼。python

py3 須要作一些改動:apache

  1. 首先你須要下載avro_python3 而不是avro
  2. 而後對代碼作如下調整(黃底部分)
    import avro.schema from avro.datafile import DataFileReader, DataFileWriter from avro.io import DatumReader, DatumWriter schema = avro.schema.Parse(open("user.avsc", "rb").read()) writer = DataFileWriter(open("users.avro", "wb"), DatumWriter(), schema) writer.append({"name": "Alyssa", "favorite_number": 256}) writer.append({"name": "Ben", "favorite_number": 7, "favorite_color": "red"}) writer.close() reader = DataFileReader(open("users.avro", "rb"), DatumReader()) for user in reader: print(user) reader.close()
  3. user.avsc 文件哪來?
直接將文章中的如下內容存到文件中就好了。
{"namespace": "example.avro",
 "type": "record",
 "name": "User",
 "fields": [
     {"name": "name", "type": "string"},
     {"name": "favorite_number",  "type": ["int", "null"]},
     {"name": "favorite_color", "type": ["string", "null"]}
 ]
}
相關文章
相關標籤/搜索