import json
# 假设用户输入的字典数据
data = {'name': 'John', 'age': 30}
# 打开一个文件用于写入,'w' 表示写入模式
with open('output.json', 'w') as file:
# 使用 json.dump() 方法将字典数据写入文件
json.dump(data, file)
import json
:导入Python的JSON模块,该模块提供了处理JSON数据的方法。
data = {'name': 'John', 'age': 30}
:定义一个字典变量 data
,模拟用户输入的字典形式数据。
with open('output.json', 'w') as file
:使用 with
语句打开一个名为 output.json
的文件,'w'
表示以写入模式打开文件。with
语句会在代码块结束后自动关闭文件,无需手动调用 file.close()
。
json.dump(data, file)
:json.dump()
方法将字典 data
转换为JSON格式,并写入到打开的文件 file
中。这样就将字典数据保存到了文件 output.json
中。