Python中的open与JSON的使用

目录

1 使用 open 函数进行文件操作

2 使用 json 模块进行 JSON 数据处理:

2.1 写入JSON 文件

2.2 读取JSON 文件

在 Python 中,open 函数和 json 模块常用于文件的读写和 JSON 数据的处理。

1 使用 open 函数进行文件操作

open 函数用于打开文件,它的基本语法为:

  • file: 文件路径或文件对象。
  • mode: 打开文件的模式,常见的模式包括 'r'(读取)、'w'(写入)、'a'(追加)等。
  • encoding: 文件编码,通常使用 'utf-8'。


# 写入文件 
with open('output.txt', 'w', encoding='utf-8') as file: 
    file.write('Hello, World!')

Python中的open与JSON的使用_第1张图片

# 读取文件 
with open('example.txt', 'r', encoding='utf-8') as file: 
    content = file.read() 
    print(content) 

Python中的open与JSON的使用_第2张图片

2 使用 json 模块进行 JSON 数据处理

json 模块用于处理 JSON 格式的数据,提供了 loaddump 等函数。

2.1 写入JSON 文件:

import json
# 打开文件
with open("data.txt", "w") as f:
    # w方式打开文件,文件不存在创建文件并写入
    result = "hello world"
    # dump 方法写入文件   前面为内容,后面为文件
    json.dump(result, f)

2.2 读取JSON 文件:

# 以只读的方式打开文件
with open("data.txt", "r") as f:
    # 将文件读取并打印
    content = json.load(f)
    print(content)

Python中的open与JSON的使用_第3张图片

Python中的open与JSON的使用_第4张图片

你可能感兴趣的:(json,python,开发语言)