python 读写json文件
时间: 2023-10-04 13:12:02 浏览: 113
你可以使用Python的内置模块`json`来读写JSON文件。下面是一个示例:
```python
import json
# 读取JSON文件
with open('data.json', 'r') as file:
data = json.load(file)
# 修改数据
data['name'] = 'Alice'
data['age'] = 25
# 写入JSON文件
with open('data.json', 'w') as file:
json.dump(data, file)
```
在这个示例中,我们首先使用`json.load()`函数从文件中加载JSON数据并存储在变量`data`中。然后,我们对`data`进行修改,例如修改"name"和"age"字段的值。最后,我们使用`json.dump()`函数将更新后的数据写回到文件中。
记得将`data.json`替换为你自己的JSON文件路径。
相关问题
Python读写json文件
在Python中,你可以使用内置的json模块来读写JSON文件。下面是一个简单的例子:
```python
import json
# 读取JSON文件
def read_json_file(file_path):
with open(file_path, 'r') as file:
data = json.load(file)
return data
# 写入JSON文件
def write_json_file(data, file_path):
with open(file_path, 'w') as file:
json.dump(data, file, indent=4)
# 示例:读取JSON文件
json_data = read_json_file('data.json')
print(json_data)
# 示例:写入JSON文件
data = {'name': 'John', 'age': 30, 'city': 'New York'}
write_json_file(data, 'output.json')
```
上述代码中,`read_json_file`函数用于从JSON文件中读取数据,`write_json_file`函数用于将数据写入JSON文件。你可以根据需要修改文件路径和文件名。
python读写json文件
### 使用Python进行JSON文件的读写操作
#### 读取JSON文件
为了处理JSON数据,可以利用Python内置的`json`包。此包提供了多种函数来编码和解码JSON数据[^1]。
下面是一个简单的例子展示如何加载并解析一个JSON文件:
```python
import json
with open('data.json') as f:
data = json.load(f)
print(data)
```
这段代码打开名为`data.json`的文件,并通过调用`json.load()`方法将其内容转换成Python字典对象存储于变量`data`中以便进一步访问或修改。
#### 编写JSON文件
同样地,在完成对数据的操作之后,可以通过如下方式保存更改回新的或是原有的JSON文件内:
```python
new_data = {
"name": "Alice",
"age": 25,
"city": "Beijing"
}
with open('output.json', 'w') as f:
json.dump(new_data, f, indent=4)
```
这里创建了一个新字典`new_data`表示要序列化的结构化数据;接着使用`json.dump()`把该字典的内容按照指定缩进格式写入到`output.json`文件里去。
阅读全文
相关推荐










