类型错误:需要类似字节的对象,而不是“str”——在 Python 中保存 JSON 数据

2023-12-20

我从 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()文档 https://docs.python.org/3/library/json.html#json.dump:

json 模块始终生成 str 对象,而不是 bytes 对象。所以,fp.write()必须支持str输入。

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

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

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

如果您要将多个 JSON 文档写入该文件,至少放一个newline在每个文档之间,使其成为JSON 行文件 http://jsonlines.org/;这是更容易再次解析 https://stackoverflow.com/questions/12451431/loading-and-parsing-a-json-file-with-multiple-json-objects-in-python稍后的:

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')

或者,将所有内容放入顶级对象(例如映射或列表)中,然后编写single对象到文件以创建有效的 JSON 文档。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类型错误:需要类似字节的对象,而不是“str”——在 Python 中保存 JSON 数据 的相关文章

随机推荐