从文件中读取 bytearray 格式的字符串到 python

reading bytearray formatted strings from a file into python

我有一个文本文件,每行都有类似字节数组的格式化字符串,例如: b'{"delete":{"status":{"id":554377123205378048,"id_str":"554377123205378048","user_id":981513812,"user_id_str":" 981513812"},"timestamp_ms":"1508108338761"}}'

(这来自使用 "python twitterstream.py > output.txt" 等命令行放入文本文件的流式 Twitter 数据)

我现在正在尝试读取每一行并在其上使用 json.loads() 来获取该行应该是的字典。

如果我使用 line = open('output.txt').readline() 我会得到一个如下所示的字符串: 'b\'{"delete":{"status":{"id":554377123205378048,"id_str":"554377123205378048","user_id":981513812,"user_id_str":"981513812"},"timestamp_ms":"1508108338761"}}\'\n'

注意像 'b\' 这样添加的额外转义序列。 json.loads() 无法再解析此行。如果我手动将内容复制到 python 控制台,我可以让它解析原始行,这样该行本身就可以了。我的文件 I/O 是怎么回事把它弄乱了?

此外,当我手动将行复制到变量时,它被保存为字节数组类型(字节),所以我想问题是如何让 python 以文字形式读取文件行写入的字节数组?

>>> ast.literal_eval("""b'{"delete":{"status":{"id":554377123205378048,"id_str":"554377123205378048","user_id":981513812,"user_id_str":"981513812"},"timestamp_ms":"1508108338761"}}'""")
b'{"delete":{"status":{"id":554377123205378048,"id_str":"554377123205378048","user_id":981513812,"user_id_str":"981513812"},"timestamp_ms":"1508108338761"}}'
>>> json.loads(ast.literal_eval("""b'{"delete":{"status":{"id":554377123205378048,"id_str":"554377123205378048","user_id":981513812,"user_id_str":"981513812"},"timestamp_ms":"1508108338761"}}'""").decode('utf-8'))
{'delete': {'status': {'user_id_str': '981513812', 'id_str': '554377123205378048', 'id': 554377123205378048, 'user_id': 981513812}, 'timestamp_ms': '1508108338761'}}