如何使用Python函数来读写JSON格式的文件?
发布时间:2023-07-04 11:56:37
在Python中,可以使用内置的 json 模块来读写 JSON 格式的文件。下面是一个示例,演示了如何使用 Python 函数来读写 JSON 格式的文件。
1. 导入 json 模块:
import json
2. 读取 JSON 文件到 Python 对象中:
def read_json_file(file_path):
with open(file_path, 'r') as file:
data = json.load(file)
return data
在此示例中,file_path 是 JSON 文件的路径。json.load() 函数用于将 JSON 文件读取为 Python 对象。
3. 将 Python 对象写入 JSON 文件中:
def write_json_file(file_path, data):
with open(file_path, 'w') as file:
json.dump(data, file)
在此示例中,file_path 是 JSON 文件的路径,data 是要写入文件的 Python 对象。json.dump() 函数用于将 Python 对象写入 JSON 文件。
4. 示例用法:
# 读取 JSON 文件
json_data = read_json_file('data.json')
print(json_data)
# 修改数据
json_data['name'] = 'John Doe'
# 将修改后的数据写入 JSON 文件
write_json_file('data.json', json_data)
在此示例中,假设有一个名为 data.json 的 JSON 文件。首先,使用 read_json_file() 函数读取文件内容,并将其存储在变量 json_data 中。然后,可以修改数据,并使用 write_json_file() 函数将修改后的数据写入文件中。
Python 的 json 模块提供了其他许多功能,比如处理 JSON 字符串、处理复杂嵌套的 JSON 数据等等。可以参考官方文档来了解更多详细的用法和示例:[官方文档](https://docs.python.org/3/library/json.html)
