gpt4 book ai didi

python - TypeError: a bytes-like object is required, not 'str' – 在Python中保存JSON数据

转载 作者:太空宇宙 更新时间:2023-11-04 08:39:07 29 4
gpt4 key购买 nike

我正在从 Twitter 获取 json 格式的数据并将其存储在一个文件中。

consumer_key = 'Consumer KEY'
consumer_secret = 'Secret'
access_token = 'Token'
access_secret = 'Access Secret'

auth = OAuthHandler(consumer_key, consumer_secret)

auth.set_access_token(access_token, access_secret)

api = tweepy.API(auth)

os.chdir('Path')
file = open('TwData.json','wb')

for status in tweepy.Cursor(api.home_timeline).items(15):
simplejson.dump(status._json,file,sort_keys = True)
file.close

但我收到以下错误:

Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Users/abc/anaconda/lib/python3.6/json/__init__.py", line 180, in dump
fp.write(chunk)
TypeError: a bytes-like object is required, not 'str'

最佳答案

来自json.dump() documentation :

The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.

您以二进制模式打开文件。不要那样做,从文件模式中删除 b:

file = open('TwData.json','w')

最好使用绝对路径而不是更改工作目录,如果您将文件用作上下文管理器(使用 with 语句),它会自动为您关闭该 block 已完成。这有助于避免诸如忘记实际调用 file.close() 方法之类的错误。

如果您要将多个 JSON 文档写入文件,至少在每个文档之间放置一个换行符,使其成为 JSON lines file ;这是much easier to parse again稍后:

with open('Path/TWData.json', 'w') as file:    
for status in tweepy.Cursor(api.home_timeline).items(15):
json.dump(status._json, file, sort_keys=True)
file.write('\n')

或者,将所有内容放入映射或列表等顶级对象中,然后将该单个对象写入文件以创建有效的 JSON 文档。

关于python - TypeError: a bytes-like object is required, not 'str' – 在Python中保存JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46153768/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com