我正在从 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'
请您参考如下方法:
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 文档。
