Python怎么把json数据保存到文件

在Python中,可以使用json模块将JSON数据保存到文件中。具体步骤如下:

首先,导入json模块。

import json

创建一个包含JSON数据的Python字典或列表。

data = {'name': 'John', 'age': 30, 'city': 'New York'}

使用json.dump()函数将JSON数据保存到文件中。该函数接受两个参数:JSON数据和文件对象。可以使用open()函数创建一个文件对象。

with open('data.json', 'w') as file:
    json.dump(data, file)

在上述代码中,'data.json'是要保存JSON数据的文件名,'w'表示以写入模式打开文件。

完整示例代码如下:

import json

data = {'name': 'John', 'age': 30, 'city': 'New York'}

with open('data.json', 'w') as file:
    json.dump(data, file)

运行上述代码后,会在当前目录下创建一个名为data.json的文件,并将JSON数据保存到该文件中。

阅读剩余
THE END