对于Python3,我遵循@Martijn Pieters 的代码有了这个:
import gzip
import json
# writing
with gzip.GzipFile(jsonfilename, 'w') as fout:
for i in range(N):
uid = "whatever%i" % i
dv = [1, 2, 3]
data = json.dumps({
'what': uid,
'where': dv})
fout.write(data + '\n')
但这会导致错误:
Traceback (most recent call last):
...
File "C:\Users\Think\my_json.py", line 118, in write_json
fout.write(data + '\n')
File "C:\Users\Think\Anaconda3\lib\gzip.py", line 258, in write
data = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'str'
对正在发生的事情有什么想法吗?
这里有四个转变步骤。
- Python 数据结构(嵌套字典、列表、字符串、数字、布尔值)
- 包含该数据结构的序列化表示形式的 Python 字符串(“JSON”)
- 包含该字符串表示形式的字节列表(“UTF-8”)
- 包含前一个字节列表(“gzip”)的更短表示的字节列表
那么让我们一一执行这些步骤。
import gzip
import json
data = []
for i in range(N):
uid = "whatever%i" % i
dv = [1, 2, 3]
data.append({
'what': uid,
'where': dv
}) # 1. data
json_str = json.dumps(data) + "\n" # 2. string (i.e. JSON)
json_bytes = json_str.encode('utf-8') # 3. bytes (i.e. UTF-8)
with gzip.open(jsonfilename, 'w') as fout: # 4. fewer bytes (i.e. gzip)
fout.write(json_bytes)
请注意添加"\n"
这里完全是多余的。它不会破坏任何东西,但除此之外它就没有用处了。我添加它只是因为您的代码示例中有它。
阅读的效果恰恰相反:
with gzip.open(jsonfilename, 'r') as fin: # 4. gzip
json_bytes = fin.read() # 3. bytes (i.e. UTF-8)
json_str = json_bytes.decode('utf-8') # 2. string (i.e. JSON)
data = json.loads(json_str) # 1. data
print(data)
当然,这些步骤可以组合起来:
with gzip.open(jsonfilename, 'w') as fout:
fout.write(json.dumps(data).encode('utf-8'))
and
with gzip.open(jsonfilename, 'r') as fin:
data = json.loads(fin.read().decode('utf-8'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)