当前位置: 首页 > article >正文

【python实操】python小程序之文件操作的JSON读取和JSON修改

引言

python小程序之文件操作的JSON读取和JSON修改

文章目录

  • 引言
  • 一、文件操作之JSON读取
    • 1.1 概念
      • 1.1.1 打开文件
      • 1.1.2 读取文件
      • 1.1.3 写入文件
      • 1.1.4 关闭文件
      • 1.1.5 例子
      • 1.1.6 读取 JSON 文件
      • 1.1.7 写入 JSON 文件
      • 1.1.8 修改 JSON 数据
      • 1.1.9 追加数据到 JSON 文件
      • 1.1.10 处理嵌套的 JSON 数据
      • 1.1.11 使用 `json.loads()` 和 `json.dumps()`
      • 1.1.12 总结
    • 1.2 题目
    • 1.3 代码
    • 1.3 代码解释
      • 1.3.1 总结
  • 二、JSON修改
    • 2.1 题目
    • 2.2 代码
    • 2.3 代码解释
      • 2.3.1 总结
  • 三、思考
    • 3.1 JSON 读取
    • 3.2 JSON修改

一、文件操作之JSON读取

1.1 概念

Python 提供了多种方式来处理文件操作,包括读取、写入和追加文件内容等。下面是一些基本的文件操作方法:

1.1.1 打开文件

要打开一个文件,可以使用内置的 open() 函数。open() 函数需要两个参数:文件名(字符串)和模式(字符)。模式指定了文件打开的方式

常见的模式有:

  • 'r' - 只读模式,默认值。如果文件不存在,会抛出 FileNotFoundError
  • 'w' - 写入模式。如果文件存在,则会被覆盖;如果文件不存在,则创建新文件
  • 'a' - 追加模式。如果文件存在,文件指针将被放置在文件末尾;如果文件不存在,则创建新文件
  • 'b' - 二进制模式
  • 't' - 文本模式,默认值
  • '+' - 更新模式(可读可写)

例如,以只读模式打开一个文本文件:

file = open('example.txt', 'r')

1.1.2 读取文件

一旦文件被打开,可以使用不同的方法来读取文件内容,如 read(), readline(), 或 readlines()

  • read(size) - 从文件中读取指定数量的数据并返回为字符串。如果没有指定 size 或者指定为负数,则读取到文件结束
  • readline() - 从文件中读取一行数据
  • readlines() - 从文件中读取所有行,并返回一个列表,其中每个元素代表文件中的一行

示例代码:

with open('example.txt', 'r') as file:
    content = file.read()  # 读取整个文件内容
    print(content)

1.1.3 写入文件

要向文件中写入数据,可以使用 write() 方法或 writelines() 方法

  • write(string) - 将字符串写入文件
  • writelines(sequence) - 将序列中的字符串依次写入文件

示例代码:

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() 方法来关闭它

file = open('example.txt', 'r')
# ... do something with the file
file.close()

或者使用 with 语句:

with open('example.txt', 'r') as file:
    # 文件在这里被自动管理
    # 不需要调用 file.close()

1.1.5 例子

有一个完整的例子,展示了如何读取一个文件,修改其内容,然后将结果写入另一个文件:

# 读取原文件
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() 方法

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() 方法

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 数据并保存回文件,可以先读取文件,修改数据,然后写回文件

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 文件,并且想添加一个新的用户:

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 文件,每个用户有多个属性

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 格式的字符串
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 代码

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 文件,并从中提取特定字段的值

  1. 导入 json 模块

    import json
    

    导入 Python 的 json 模块,用于处理 JSON 数据

  2. 打开并读取 JSON 文件

    with 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
  3. 打印 b 的类型

    print(type(b))
    

    打印变量 b 的类型,以便确认它是一个字典还是列表

  4. 获取并打印 name 字段的值

    print(b.get('name'))
    
    • 使用 b.get('name') 获取 b 中键为 'name' 的值
    • 如果键 'name' 存在于 b 中,则返回其对应的值;否则返回 None
  5. 获取并打印 like 字段的值

    print(b.get('like'))
    
    • 使用 b.get('like') 获取 b 中键为 'like' 的值
    • 如果键 'like' 存在于 b 中,则返回其对应的值;否则返回 None
  6. 获取并打印 address 字段中的 province

    print(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 代码

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 文件

  1. 导入 json 模块

    import json
    

    导入 python 的 json 模块,用于处理 JSON 数据

  2. 读取 JSON 文件

    with 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
  3. 打印原始的 JSON 数据

    print(x)
    

    打印从文件中读取的原始 JSON 数据,以便查看其内容

  4. 修改 name 字段的值

    for 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'
  5. 打印修改后的 JSON 数据

    print(x)
    

    打印修改后的 JSON 数据,以便查看修改是否成功

  6. 将修改后的数据写回 JSON 文件

    with 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 文件:使用 openjson.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 字符正确显示

http://www.kler.cn/news/353753.html

相关文章:

  • 在wpf 中 用mvvm 的方式 绑定 鼠标事件
  • Java笔试03
  • Linux 线程概念及线程控制
  • 系统缺失mfc140.dll的修复方法,有效修复错误mfc140.dll详细步骤
  • VLAN概述
  • 阻塞I/O与非阻塞I/O
  • 408算法题leetcode--第36天
  • 从HCI和空口分析HFP通话和eSCO建立
  • 【进阶OpenCV】 (18)-- Dlib库 --人脸关键点定位
  • 如何高效解锁业务数据价值:多云时代应该怎么构建新一代数据平台架构
  • Allegro 小技巧
  • 二叉树与堆讲解
  • unity动态批处理
  • Spring Boot知识管理系统:安全与合规性
  • linux红帽基础命令
  • 【力扣热题100】3194. 最小元素和最大元素的最小平均值【Java】
  • mysql--数据表的操作
  • AI Weekly#1:过去一周重要的AI资讯汇总
  • 基于知识图谱的宁夏非遗问答系统
  • URL路径以及Tomcat本身引入的jar包会导致的 SpringMVC项目 404问题、Tomcat调试日志的开启及总结