所以我收到了这样的数据:
[{
'Status': 0,
'Button': False,
'Message': None,
'Id': None,
'hu': 0,
'Mode': 'LocModePresence',
'mac': '00011171815E',
'mapId': '17_1_0',
'Seq': 236,
'tam': False,
'temperature': 0.0,
'time': 1603797352911,
'type': 'TTT',
'x': 2716.0,
'y': 648.0,
'zone': '301990146'
}, {
'Status': 0,
'Button': False,
'Message': '6e0002000c00',
'Id': '3_2',
'hu': 0,
'Mode': 'LocModePresence',
'mac': '00011171815E',
'mapId': '17_1_0',
'Seq': 237,
'tam': False,
'temperature': 0.0,
'time': 1603797357105,
'type': 'TTT',
'x': 2716.0,
'y': 648.0,
'zone': '301990146'
}]我想把它写到JSON文件中:
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(my_data, f, ensure_ascii=False, indent=4)如果我想将这个数据作为字符串(出于调试原因),为什么当我将它放入2 '中时,请使用this show me error
illegal target for variable annotation我希望能够将它写到我的磁盘上,也可以读取它来与我将获得的另一个文件进行比较(而且这个文件也需要写在磁盘上)
发布于 2020-10-27 20:03:13
当你从文件中读取时,你应该使用read()。
read() readline()和readline()之间的区别记录如下:
When should I ever use file.read() or file.readlines()?
import json
my_data = [
{
'Status': 0,
'Button': False,
'Message': None,
'Id': None,
'hu': 0,
'Mode': 'LocModePresence',
'mac': '00011171815E',
'mapId': '17_1_0',
'Seq': 236,
'tam': False,
'temperature': 0.0,
'time': 1603797352911,
'type': 'TTT',
'x': 2716.0,
'y': 648.0,
'zone': '301990146',
},
{
'Status': 0,
'Button': False,
'Message': '6e0002000c00',
'Id': '3_2',
'hu': 0,
'Mode': 'LocModePresence',
'mac': '00011171815E',
'mapId': '17_1_0',
'Seq': 237,
'tam': False,
'temperature': 0.0,
'time': 1603797357105,
'type': 'TTT',
'x': 2716.0,
'y': 648.0,
'zone': '301990146',
},
]
if __name__ == '__main__':
with open('data.json', 'w', encoding='utf-8') as _file:
json.dump(my_data, _file, ensure_ascii=False, indent=4)
with open('data.json', 'r', encoding='utf-8') as _file:
str_content = _file.read()
print(type(str_content))
json_content = json.loads(str_content)
print(type(json_content))https://stackoverflow.com/questions/64553891
复制相似问题