Python 3 脚本:将 Msgpack 文件转换为 JSON 文件
以下是将 Msgpack 二进制文件转换为 JSON 文件的 Python 3 脚本:
import msgpack
import json
import os
# 输入文件名
filename = input('请输入要转换的文件名:')
# 检查文件是否存在
if not os.path.exists(filename):
print('文件不存在!')
exit()
# 检查文件扩展名是否为 msgpack
if not filename.endswith('.msgpack'):
print('文件格式错误!')
exit()
# 读取 msgpack 文件并转换成 json 格式
with open(filename, 'rb') as f:
data = msgpack.unpack(f, raw=False)
json_data = json.dumps(data, indent=4)
# 写入 json 文件
json_filename = filename.replace('.msgpack', '.json')
with open(json_filename, 'w') as f:
f.write(json_data)
print('转换完成!输出文件名为:', json_filename)
使用方法:
- 将上述脚本复制到 Python 编辑器中并保存为 .py 文件。
- 在控制台中运行脚本。
- 输入要转换的 Msgpack 文件名,包括扩展名。
- 程序将转换文件并输出 JSON 文件名。
原文地址: https://www.cveoy.top/t/topic/npb1 著作权归作者所有。请勿转载和采集!