【问题标题】:From gzip to json to dataframe to csv从 gzip 到 json 到 dataframe 到 csv
【发布时间】:2019-12-18 11:38:08
【问题描述】:

我正在尝试从开放 API 获取一些数据:

https://data.brreg.no/enhetsregisteret/api/enheter/lastned 

但我很难理解不同类型的对象和转换的顺序。是stringsbytes,是BytesIO 还是StringIO,是decode('utf-8) 还是@ 987654331@等...?

到目前为止:

url_get = 'https://data.brreg.no/enhetsregisteret/api/enheter/lastned'


with urllib.request.urlopen(url_get) as response:
    encoding = response.info().get_param('charset', 'utf8')
    compressed_file = io.BytesIO(response.read())
    decompressed_file = gzip.GzipFile(fileobj=compressed_file)

现在卡住了,下一行代码该怎么写?

json_str = json.loads(decompressed_file.read().decode('utf-8'))

我的解决方法是,如果我将它写为 json 文件,然后再次读入并转换为 df,那么它就可以工作了:

with io.open('brreg.json', 'wb') as f:
    f.write(decompressed_file.read())

with open(f_path, encoding='utf-8') as fin:
    d = json.load(fin)

df = json_normalize(d)

with open('brreg_2.csv', 'w', encoding='utf-8', newline='') as fout:
    fout.write(df.to_csv())

我发现了很多关于它的帖子,但我仍然很困惑。第一个解释得很好,但我仍然需要用勺子喂食。

Python 3, read/write compressed json objects from/to gzip file

TypeError when trying to convert Python 2.7 code to Python 3.4 code

How can I create a GzipFile instance from the “file-like object” that urllib.urlopen() returns?

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

【问题讨论】:

  • 您的代码存在哪些问题?在我看来,您在 GZipFile 对象上缺少 .decompress()
  • 我得到 AttributeError: 'bytes' object has no attribute 'encode'
  • 对不起,这是我得到的回溯: AttributeError: 'str' object has no attribute 'read'

标签: python json pandas gzip urllib


【解决方案1】:

使用decompress 函数而不是GZipFile 类来解压缩文件对我来说效果很好,但还不知道为什么...

import urllib.request
import gzip
import io
import json

url_get = 'https://data.brreg.no/enhetsregisteret/api/enheter/lastned'


with urllib.request.urlopen(url_get) as response:
    encoding = response.info().get_param('charset', 'utf8')
    compressed_file = io.BytesIO(response.read())
    decompressed_file = gzip.decompress(compressed_file.read())
    json_str = json.loads(decompressed_file.decode('utf-8'))

编辑,实际上以下对我来说也很好用,这似乎是您的确切代码... (进一步编辑,事实证明这不是您的确切代码,因为您的最后一行在 with 块之外,这意味着 response 在需要时不再打开 - 请参阅评论线程)

import urllib.request
import gzip
import io
import json

url_get = 'https://data.brreg.no/enhetsregisteret/api/enheter/lastned'


with urllib.request.urlopen(url_get) as response:
    encoding = response.info().get_param('charset', 'utf8')
    compressed_file = io.BytesIO(response.read())
    decompressed_file = gzip.GzipFile(fileobj=compressed_file)
    json_str = json.loads(decompressed_file.read().decode('utf-8'))

【讨论】:

  • 谢谢,它现在可以正常工作了!我了解到生命太短暂,无法思考为什么事情会起作用,因为有很多事情不会;)
  • 啊,所以在我的代码中,最后一行在 with 语句之外,但我不明白为什么这应该是一个问题。无论如何,请参考上面的报价。
  • 这听起来似乎是问题的原因。当然,GzipFile 只是作为底层文件对象的“包装器”,我可以想象 BytesIO 也是如此。在这种情况下,所有这些行都取决于“响应”是否仍处于打开状态。
猜你喜欢
  • 2020-12-10
  • 2021-07-04
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 2017-04-29
  • 2020-01-15
  • 2016-05-10
相关资源
最近更新 更多