使用 Python 读取、写入和操作 JSON 文件
JSON(JavaScript 对象表示法)是一种流行的数据交换格式,易于人类读写。在编程领域与 Web API 或 HTTP 请求交互时,JSON 通常会发挥作用。Python 通过 json 模块为处理 JSON 文件提供了内置支持。在本文中,我们将讨论如何使用 Python 读取、写入和操作 JSON 文件。
花椒壳-愿您平安健康 - 花椒壳资源网
读取 JSON 文件
要在 Python 中读取 JSON 文件,您可以按照以下步骤操作:
- 导入 json 模块。
- 使用 Python 的 open() 函数打开 JSON 文件,并将 mode 设置为 r。
- 使用 json.load() 函数将文件的内容加载为 Python 字典。
下面是一个示例代码片段,演示了如何读取 JSON 文件:
import json
# Open the JSON file
with open('data.json') as f:
data = json.load(f)
# Print the data (it will be stored as a Python dictionary)
print(data)
编写 JSON 文件
要在 Python 中将数据写入 JSON 文件,您也可以使用 json 模块。以下是将数据写入 JSON 文件的步骤:
- 定义要写入 Python 字典的数据。
- 使用 Python 的 open() 函数打开一个新文件。
- 使用 json.dump() 函数将字典数据以 JSON 格式写入文件。
下面是一个示例代码片段,演示如何将数据写入 JSON 文件:
import json
# Define the data as a Python dictionary
data = {
'name': 'Bob',
'age': '25',
'city': 'Los Angeles'
}
# Write data to a JSON file
with open('output.json', 'w') as f:
json.dump(data, f)
您可以读取 output.json 文件,通过添加新的键值对来修改数据字典,然后将其另存为另一个 JSON 文件。以下是实现此目的的示例代码片段:
# Read the data from the written file and print it
with open('output.json') as f:
output_data = json.load(f)
print(output_data)
# Modify the data by adding a new key-value pair
output_data['job'] = 'Engineer'
# Write the modified data to a new JSON file
with open('modified_output.json', 'w') as f:
json.dump(output_data, f)
# Read the modified data from the newly written file and print it
with open('modified_output.json') as f:
modified_data = json.load(f)
print('Modified data:', modified_data)
在此代码片段中:
- 我们首先从 output.json 文件中读取数据。
- 然后,我们通过添加新的键值对来修改 output_data 字典。
- 然后,修改后的数据将写入名为 modified_output.json 的新 JSON 文件。
- 最后,我们从 modified_output.json 读取修改后的数据并打印出来。
花椒壳-愿您平安健康 - 花椒壳资源网花椒壳资源网,资源下载,主要提供资源、设计素材、音乐、视频、图片等一切与互联网有关的资源https://www.xinliu.vip
结论
总之,Python 的 json 模块使处理 JSON 文件变得简单。您可以使用 Python 的内置函数读取、写入和操作 JSON 数据,使其成为在 Python 项目中处理 JSON 数据的强大工具。