Python JSON文件读写
引言
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它以易于人阅读和编写的文本格式来表示数据。在Python中,我们可以使用内置的json
模块来处理JSON文件的读取和写入操作。本文将详细介绍如何使用Python读取和写入JSON文件。
读取JSON文件
在Python中,我们可以使用json
模块的load()
函数来读取JSON文件。下面是读取JSON文件的示例代码:
import json
# 读取JSON文件
def read_json_file(file_name):
with open(file_name, 'r', encoding='utf-8') as file:
data = json.load(file)
return data
# 测试读取JSON文件
data = read_json_file('data.json')
print(data)
在上述示例代码中,我们定义了一个read_json_file()
函数来读取JSON文件。该函数接受一个文件名作为参数,并使用with open()
语句打开文件。然后,使用json.load()
函数加载文件中的JSON数据,并将其返回。
写入JSON文件
与读取JSON文件类似,我们可以使用json
模块的dump()
函数来写入JSON文件。下面是写入JSON文件的示例代码:
import json
# 写入JSON文件
def write_json_file(file_name, data):
with open(file_name, 'w', encoding='utf-8') as file:
json.dump(data, file, indent=4)
# 测试写入JSON文件
data = {'name': 'John', 'age': 30, 'city': 'New York'}
write_json_file('data.json', data)
在上述示例代码中,我们定义了一个write_json_file()
函数来写入JSON文件。该函数接受一个文件名和要写入的数据作为参数,并使用with open()
语句打开文件。然后,使用json.dump()
函数将数据写入文件中。通过设置indent
参数为4,可使输出的JSON文件有更好的可读性。
JSON数据的访问和修改
读取JSON文件后,我们可以使用Python的字典操作来访问和修改JSON数据。下面是对JSON数据进行访问和修改的示例代码:
import json
# 读取JSON文件
def read_json_file(file_name):
with open(file_name, 'r', encoding='utf-8') as file:
data = json.load(file)
return data
# 访问和修改JSON数据
data = read_json_file('data.json')
print(data['name']) # 输出:John
data['age'] = 35
print(data['age']) # 输出:35
# 写入修改后的JSON数据
write_json_file('data.json', data)
在上述示例代码中,我们首先使用之前定义的read_json_file()
函数读取JSON文件。然后,通过字典索引的方式访问和修改JSON数据。最后,我们调用之前定义的write_json_file()
函数将修改后的数据写回JSON文件中。
示例代码运行结果
对于上面的示例代码,我们可以使用以下JSON文件作为输入数据进行测试:
data.json
{
"name": "John",
"age": 30,
"city": "New York"
}
运行示例代码后,输出如下:
John
35
总结
本文介绍了如何使用Python的json
模块来读取和写入JSON文件。我们通过示例代码演示了读取和写入JSON文件的步骤,并展示了如何访问和修改JSON数据。