Discuss / Python / json
import json
d={"name":"xxxx","age":21}
json_data=json.dumps(d)
print(json_data)
print(json.loads(json_data))
with open("seralize_data.txt",'wb') as f:
    json.dump(d,f)
with open("seralize_data.txt",'rb') as f:
    print(json.load(f))

Result:

{"age": 21, "name": "xxxx"}
{'age': 21, 'name': 'xxxx'}
Traceback (most recent call last):
  File "./seralization.py", line 35, in <module>
    json.dump(d,f)
  File "/opt/python3.5/lib/python3.5/json/__init__.py", line 179, in dump
    fp.write(chunk)
TypeError: a bytes-like object is required, not 'str'

any one can tell me why?

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

用'r'不是'rb'

丁磊BLH

#3 Created at ... [Delete] [Delete and Lock User]

为什么我照这样做不能用with把json文件写入文本里啊?分开来写就可以。求指教

我理解json化就是字符串化而不是二进制化了所以保存读取时不能带参数“b”


  • 1

Reply