TypeError:需要一个类似字节的对象,而不是'str'–在Python中保存JSON数据 [英] TypeError: a bytes-like object is required, not 'str' – Saving JSON data in Python
问题描述
我正在以json格式从twitter获取数据并将其存储在文件中.
I am getting data from twitter in json format and storing the same in a file.
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
但是我遇到了以下错误:
But I am getting the below error:
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模块始终生成str对象,而不生成byte对象.因此, The json module always produces str objects, not bytes objects. Therefore, 您以二进制模式打开了文件.不要这样做,从文件模式中删除 You opened the file in binary mode. Don't do that, remove the 最好使用绝对路径而不是更改工作目录,并且如果您将该文件用作上下文管理器(带有 It's better to use an absolute path rather than change the working directory, and if you used the file as a context manager (with the 如果要向该文件写入多个JSON文档,请在每个文档之间至少放置一个 newline ,使其成为 JSON行文件;这是更容易再次解析稍后: And if you are going to write multiple JSON documents to the file, at least put a newline between each document, making it a JSON lines file; this is much easier to parse again later on: 或者,将所有内容放入映射或列表之类的顶级对象中,并将该单个对象写入文件中,以创建有效的JSON文档. Alternatively, put everything into a top-level object like mapping or list, and write that single object to the file to create a valid JSON document. 这篇关于TypeError:需要一个类似字节的对象,而不是'str'–在Python中保存JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!fp.write()
必须支持str输入.
fp.write()
must support str input.b
:b
from the file mode:file = open('TwData.json','w')
with
语句),则在完成块后将自动为您关闭该文件.这样可以避免出现诸如忘记实际调用file.close()
方法之类的错误.with
statement), it'll be automatically closed for you when the block is done. That helps avoid errors like forgetting to actually call the file.close()
method.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')