python 以json格式写入json文件
时间: 2023-07-05 08:31:40 浏览: 116
在 Python 中,可以使用 `json.dump()` 函数将 JSON 数据写入 JSON 文件。该函数的语法如下:
```python
import json
with open('filename.json', 'w') as f:
json.dump(data, f)
```
其中,`filename.json` 是要写入的 JSON 文件名,`data` 是要写入的 JSON 数据,`f` 是文件对象。使用 `with` 语句可以确保在写入完成后自动关闭文件。
例如,将一个字典对象写入 JSON 文件:
```python
import json
data = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as f:
json.dump(data, f)
```
这将在当前目录下创建一个名为 `data.json` 的文件,并将 `data` 字典对象以 JSON 格式写入该文件。
如果要将一个列表对象写入 JSON 文件,可以使用 `json.dump()` 函数的第三个参数 `indent` 来设置缩进:
```python
import json
data = ['apple', 'banana', 'orange']
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
```
这将在当前目录下创建一个名为 `data.json` 的文件,并将 `data` 列表对象以缩进为 4 的 JSON 格式写入该文件。
阅读全文
相关推荐


















