【问题标题】:Open json.gz in python在 python 中打开 json.gz
【发布时间】:2021-01-29 01:35:45
【问题描述】:

我正在尝试访问一个 json 对象,该对象作为压缩 gz 存储在 html 网站上。如果可能的话,我想直接用 urllib 来做这个。

这是我尝试过的:

import urllib
import json

#get the zip file
test = urllib.request.Request('http://files.tmdb.org/p/exports/movie_ids_01_27_2021.json.gz')

#unzip and read
with gzip.open(test, 'rt', encoding='UTF-8') as zipfile:
    my_object = json.loads(zipfile)

但这失败了:

TypeError: filename must be a str or bytes object, or a file

是否可以这样直接读取json(例如我不想在本地下载)。

谢谢。

【问题讨论】:

    标签: json python-3.x urllib


    【解决方案1】:

    使用请求库。 pip install requests 如果你没有的话。

    然后使用以下代码:

    import requests
    
    r = requests.get('http://files.tmdb.org/p/exports/movie_ids_01_27_2021.json.gz')
    print(r.content)
    

    r.content 将是 gzip 文件的二进制内容,但它会消耗 11352985 字节的内存 (10.8 MB),因为数据需要保存在某个地方。

    那么你可以使用

    gzip.decompress(r.content)
    

    解压 gzip 二进制文件并获取数据。解压后会消耗更大的内存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      相关资源
      最近更新 更多