引言
python小程序之文件操作的JSON读取和JSON修改
文章目录
- 引言
 - 一、文件操作之JSON读取
 - 
- [1.1 概念](#1.1 概念)
 - 
- [1.1.1 打开文件](#1.1.1 打开文件)
 - [1.1.2 读取文件](#1.1.2 读取文件)
 - [1.1.3 写入文件](#1.1.3 写入文件)
 - [1.1.4 关闭文件](#1.1.4 关闭文件)
 - [1.1.5 例子](#1.1.5 例子)
 - [1.1.6 读取 JSON 文件](#1.1.6 读取 JSON 文件)
 - [1.1.7 写入 JSON 文件](#1.1.7 写入 JSON 文件)
 - [1.1.8 修改 JSON 数据](#1.1.8 修改 JSON 数据)
 - [1.1.9 追加数据到 JSON 文件](#1.1.9 追加数据到 JSON 文件)
 - [1.1.10 处理嵌套的 JSON 数据](#1.1.10 处理嵌套的 JSON 数据)
 - [1.1.11 使用 `json.loads()` 和 `json.dumps()`](#1.1.11 使用 
json.loads()和json.dumps()) - [1.1.12 总结](#1.1.12 总结)
 
 - [1.2 题目](#1.2 题目)
 - [1.3 代码](#1.3 代码)
 - [1.3 代码解释](#1.3 代码解释)
 - 
- [1.3.1 总结](#1.3.1 总结)
 
 
 - 二、JSON修改
 - 
- [2.1 题目](#2.1 题目)
 - [2.2 代码](#2.2 代码)
 - [2.3 代码解释](#2.3 代码解释)
 - 
- [2.3.1 总结](#2.3.1 总结)
 
 
 - 三、思考
 - 
- [3.1 JSON 读取](#3.1 JSON 读取)
 - [3.2 JSON修改](#3.2 JSON修改)
 
 
一、文件操作之JSON读取
1.1 概念
Python 提供了多种方式来处理文件操作,包括读取、写入和追加文件内容等。下面是一些基本的文件操作方法:
1.1.1 打开文件
要打开一个文件,可以使用内置的 open() 函数。open() 函数需要两个参数:文件名(字符串)和模式(字符)。模式指定了文件打开的方式
常见的模式有:
'r'- 只读模式,默认值。如果文件不存在,会抛出FileNotFoundError'w'- 写入模式。如果文件存在,则会被覆盖;如果文件不存在,则创建新文件'a'- 追加模式。如果文件存在,文件指针将被放置在文件末尾;如果文件不存在,则创建新文件'b'- 二进制模式't'- 文本模式,默认值'+'- 更新模式(可读可写)
例如,以只读模式打开一个文本文件:
            
            
              python
              
              
            
          
          file = open('example.txt', 'r')
        1.1.2 读取文件
一旦文件被打开,可以使用不同的方法来读取文件内容,如 read(), readline(), 或 readlines()
read(size)- 从文件中读取指定数量的数据并返回为字符串。如果没有指定 size 或者指定为负数,则读取到文件结束readline()- 从文件中读取一行数据readlines()- 从文件中读取所有行,并返回一个列表,其中每个元素代表文件中的一行
示例代码:
            
            
              python
              
              
            
          
          with open('example.txt', 'r') as file:
    content = file.read()  # 读取整个文件内容
    print(content)
        1.1.3 写入文件
要向文件中写入数据,可以使用 write() 方法或 writelines() 方法
write(string)- 将字符串写入文件writelines(sequence)- 将序列中的字符串依次写入文件
示例代码:
            
            
              python
              
              
            
          
          with open('output.txt', 'w') as file:
    file.write("Hello, world!\n")
    file.writelines(['This is a test.\n', 'Writing to a file.'])
        1.1.4 关闭文件
完成文件操作后,应该关闭文件以释放资源。通常使用 with 语句来自动管理文件的打开和关闭,但如果你手动打开了文件,记得使用 close() 方法来关闭它
            
            
              python
              
              
            
          
          file = open('example.txt', 'r')
# ... do something with the file
file.close()
        或者使用 with 语句:
            
            
              python
              
              
            
          
          with open('example.txt', 'r') as file:
    # 文件在这里被自动管理
    # 不需要调用 file.close()
        1.1.5 例子
有一个完整的例子,展示了如何读取一个文件,修改其内容,然后将结果写入另一个文件:
            
            
              python
              
              
            
          
          # 读取原文件
with open('input.txt', 'r') as input_file:
    lines = input_file.readlines()
# 修改内容(例如,给每一行添加前缀)
modified_lines = ['Modified: ' + line for line in lines]
# 写入新文件
with open('output.txt', 'w') as output_file:
    output_file.writelines(modified_lines)
        这个例子中,首先读取了 input.txt 的所有行,然后对每一行进行了简单的修改,最后将修改后的内容写入 output.txt 文件
在所有文件中,处理 JSON 文件在 python 中是最常见的,因为 JSON 是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。Python 的标准库
json提供了处理 JSON 数据的功能
下面是一些常见的 JSON 文件操作示例:
1.1.6 读取 JSON 文件
要从 JSON 文件中读取数据并将其转换为 Python 对象(通常是字典或列表),可以使用 json.load() 方法
            
            
              python
              
              
            
          
          import json
# 打开 JSON 文件并加载内容
with open('data.json', 'r') as file:
    data = json.load(file)
# 打印加载的 JSON 数据
print(data)
        1.1.7 写入 JSON 文件
要将 python 对象(如字典或列表)写入 JSON 文件,可以使用 json.dump() 方法
            
            
              python
              
              
            
          
          import json
# 创建一个 Python 字典
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
# 将数据写入 JSON 文件
with open('output.json', 'w') as file:
    json.dump(data, file, indent=4)  # indent 参数用于美化输出格式
        1.1.8 修改 JSON 数据
如果需要修改 JSON 数据并保存回文件,可以先读取文件,修改数据,然后写回文件
            
            
              python
              
              
            
          
          import json
# 读取 JSON 文件
with open('data.json', 'r') as file:
    data = json.load(file)
# 修改数据
data['age'] = 31  # 假设我们想把年龄改为 31
# 将修改后的数据写回 JSON 文件
with open('data.json', 'w') as file:
    json.dump(data, file, indent=4)
        1.1.9 追加数据到 JSON 文件
JSON 文件本身并不支持直接追加数据,因为 JSON 文件是一个完整的对象(通常是字典或列表)。但可以通过读取文件、修改数据、然后写回文件来实现类似的效果
假设有一个包含用户列表的 JSON 文件,并且想添加一个新的用户:
            
            
              python
              
              
            
          
          import json
# 读取 JSON 文件
with open('users.json', 'r') as file:
    users = json.load(file)
# 添加新用户
new_user = {
    "id": 3,
    "name": "Alice",
    "email": "alice@example.com"
}
users.append(new_user)
# 将修改后的数据写回 JSON 文件
with open('users.json', 'w') as file:
    json.dump(users, file, indent=4)
        1.1.10 处理嵌套的 JSON 数据
JSON 数据可以是嵌套的结构。例如,可能有一个包含多个用户的 JSON 文件,每个用户有多个属性
            
            
              python
              
              
            
          
          import json
# 读取 JSON 文件
with open('nested_data.json', 'r') as file:
    data = json.load(file)
# 访问嵌套数据
for user in data['users']:
    print(f"Name: {user['name']}, Age: {user['age']}")
# 修改嵌套数据
for user in data['users']:
    if user['name'] == 'John':
        user['age'] = 32
# 将修改后的数据写回 JSON 文件
with open('nested_data.json', 'w') as file:
    json.dump(data, file, indent=4)
        1.1.11 使用 json.loads() 和 json.dumps()
json.loads(json_string):将 JSON 格式的字符串转换为 python 对象json.dumps(python_object):将 Python 对象转换为 JSON 格式的字符串
            
            
              python
              
              
            
          
          import json
# 将 JSON 字符串转换为 Python 对象
json_string = '{"name": "John", "age": 30}'
data = json.loads(json_string)
print(data)  # 输出: {'name': 'John', 'age': 30}
# 将 Python 对象转换为 JSON 字符串
data = {"name": "John", "age": 30}
json_string = json.dumps(data)
print(json_string)  # 输出: {"name": "John", "age": 30}
        1.1.12 总结
- 读取 JSON 文件 :使用 
json.load()从文件中读取 JSON 数据 - 写入 JSON 文件 :使用 
json.dump()将 Python 对象写入 JSON 文件 - 修改 JSON 数据:读取、修改、再写回文件
 - 处理嵌套的 JSON 数据:访问和修改嵌套的 JSON 结构
 - 使用 
json.loads()和json.dumps():在字符串和 python 对象之间进行转换 
1.2 题目
如何读取 JSON
1.3 代码
            
            
              python
              
              
            
          
          import json
with open('info.json', 'r', encoding='utf-8') as f:
    b = json.load(f)
    print(type(b))
    print(b.get('name'))
    print(b.get('like'))
    print(b.get('address').get('province'))
        输出结果:

1.3 代码解释
这段代码展示了如何读取一个 JSON 文件,并从中提取特定字段的值
- 
导入
json模块:pythonimport json导入 Python 的
json模块,用于处理 JSON 数据 - 
打开并读取 JSON 文件:
pythonwith open('info.json', 'r', encoding='utf-8') as f: b = json.load(f)- 使用 
open函数以只读模式 ('r') 和指定编码 (encoding='utf-8') 打开info.json文件 - 使用 
json.load(f)方法将文件内容解析为 Python 对象(通常是字典或列表),并将结果存储在变量b中 
 - 使用 
 - 
打印
b的类型:pythonprint(type(b))打印变量
b的类型,以便确认它是一个字典还是列表 - 
获取并打印
name字段的值:pythonprint(b.get('name'))- 使用 
b.get('name')获取b中键为'name'的值 - 如果键 
'name'存在于b中,则返回其对应的值;否则返回None 
 - 使用 
 - 
获取并打印
like字段的值:pythonprint(b.get('like'))- 使用 
b.get('like')获取b中键为'like'的值 - 如果键 
'like'存在于b中,则返回其对应的值;否则返回None 
 - 使用 
 - 
获取并打印
address字段中的province值:pythonprint(b.get('address').get('province'))- 首先使用 
b.get('address')获取b中键为'address'的值,假设这个值是一个字典 - 然后使用 
.get('province')获取该字典中键为'province'的值 - 如果键 
'address'或'province'不存在,则返回None 
 - 首先使用 
 
1.3.1 总结
通过这种方式,可以轻松地从 JSON 文件中提取和打印特定字段的值
二、JSON修改
2.1 题目
如何修改 JSON
2.2 代码
            
            
              python
              
              
            
          
          import json
with open('info2.json', 'r', encoding='utf-8') as f2:
    x = json.load(f2)
    print(x)
    for person in x:
        if person['name'] == 'test':
            person['name'] = 'test2'
        if person['name'] == '小明':
            person['name'] = '小明2'
    print(x)
with open('info2.json', 'w', encoding='utf-8') as file:
    json.dump(x, file, ensure_ascii=False, indent=4)
        输出结果:

2.3 代码解释
这段代码展示了如何读取一个 JSON 文件,修改其中的
name字段,然后将修改后的数据写回同一个 JSON 文件
- 
导入
json模块:pythonimport json导入 python 的
json模块,用于处理 JSON 数据 - 
读取 JSON 文件:
pythonwith open('info2.json', 'r', encoding='utf-8') as f2: x = json.load(f2)- 使用 
open函数以只读模式 ('r') 和指定编码 (encoding='utf-8') 打开info2.json文件 - 使用 
json.load(f2)方法将文件内容解析为 Python 对象(通常是列表或字典),并将结果存储在变量x中 
 - 使用 
 - 
打印原始的 JSON 数据:
pythonprint(x)打印从文件中读取的原始 JSON 数据,以便查看其内容
 - 
修改
name字段的值:pythonfor person in x: if person['name'] == 'test': person['name'] = 'test2' if person['name'] == '小明': person['name'] = '小明2'- 遍历 
x列表中的每个person字典 - 如果 
person['name']等于'test',则将其改为'test2' - 如果 
person['name']等于'小明',则将其改为'小明2' 
 - 遍历 
 - 
打印修改后的 JSON 数据:
pythonprint(x)打印修改后的 JSON 数据,以便查看修改是否成功
 - 
将修改后的数据写回 JSON 文件:
pythonwith open('info2.json', 'w', encoding='utf-8') as file: json.dump(x, file, ensure_ascii=False, indent=4)- 使用 
open函数以写入模式 ('w') 和指定编码 (encoding='utf-8') 打开info2.json文件 - 使用 
json.dump(x, file, ensure_ascii=False, indent=4)方法将修改后的 Python 对象x写入文件ensure_ascii=False参数确保非 ASCII 字符(如中文)能够正确写入文件indent=4参数用于美化输出格式,使 JSON 文件更易读
 
 - 使用 
 
2.3.1 总结
通过这种方式,可以轻松地读取、修改和保存 JSON 文件中的数据
三、思考
3.1 JSON 读取
- 导入 
json模块:用于处理 JSON 数据 - 打开并读取 JSON 文件 :使用 
open和json.load将 JSON 文件内容加载为 python 对象 - 打印 
b的类型 :确认b是一个字典 - 获取并打印 
name字段的值 :使用b.get('name')获取并打印name字段的值 - 获取并打印 
like字段的值 :使用b.get('like')获取并打印like字段的值 - 获取并打印 
address字段中的province值 :使用b.get('address').get('province')获取并打印province字段的值 
3.2 JSON修改
- 读取 JSON 文件 :使用 
json.load将文件内容解析为 python 对象 - 修改 JSON 数据:遍历数据并修改特定字段
 - 打印 JSON 数据:打印原始和修改后的数据以便验证
 - 写回 JSON 文件 :使用 
json.dump将修改后的数据写回文件,并确保非 ASCII 字符正确显示