欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > Python 读取和写入文本文件(txt)、Excel 文件和 JSON 文件的方法

Python 读取和写入文本文件(txt)、Excel 文件和 JSON 文件的方法

2025/5/15 17:16:12 来源:https://blog.csdn.net/weixin_44151034/article/details/140309282  浏览:    关键词:Python 读取和写入文本文件(txt)、Excel 文件和 JSON 文件的方法

Python 读取和写入文本文件(txt)、Excel 文件和 JSON 文件的基本方法

  • 读取/写入 txt 文件
    • 基本读取txt
      • 读取 txt 文件
      • 写入 txt 文件
      • 按行读取复杂数据
      • 处理大txt文本文件(逐行读取以节省内存)
  • 读取/写入 Excel 文件
    • 基本读取
      • 读取 Excel 文件
      • 写入 Excel 文件
      • 处理复杂 Excel 文件(多个工作表)
      • 处理大 Excel 文件(使用 `pandas` 的 `chunksize` 参数)
  • 读取/写入 JSON 文件
    • 基本读取
      • 基本读取 JSON 文件
      • 写入 JSON 文件
      • 读取嵌套数据:
    • 读取嵌套json文件:
        • 写入嵌套 JSON 数据
    • 复杂读取json文件
      • 方法一:逐行读取并解析每行 JSON
      • 方法二:逐行读取并解析嵌套 JSON
      • 方法三:处理大 JSON 文件(分块读取)
      • 方法四:使用 `jsonlines` 库

Python 提供了多种方法来读取和写入不同类型的文件,包括文本文件(txt)、Excel 文件和 JSON 文件。以下是一些常用的方法和示例代码:

读取/写入 txt 文件

基本读取txt

读取 txt 文件

  1. 使用内置的 open 函数
# 读取整个文件内容
with open('example.txt', 'r', encoding='utf-8') as file:content = file.read()print(content)# 逐行读取文件内容
with open('example.txt', 'r', encoding='utf-8') as file:for line in file:print(line.strip())

写入 txt 文件

  1. 使用内置的 open 函数
# 写入文本到文件(覆盖模式)
with open('example.txt', 'w', encoding='utf-8') as file:file.write('Hello, World!\n')# 追加文本到文件
with open('example.txt', 'a', encoding='utf-8') as file:file.write('Appending a new line.\n')

按行读取复杂数据

  1. 逐行读取并处理每行数据
# 假设我们的文件内容如下:
# Name, Age, City
# Alice, 30, New York
# Bob, 25, Los Angeleswith open('example.txt', 'r', encoding='utf-8') as file:header = file.readline().strip().split(', ')data = []for line in file:values = line.strip().split(', ')record = dict(zip(header, values))data.append(record)print(data)

处理大txt文本文件(逐行读取以节省内存)

# 逐行读取大文件
with open('large_file.txt', 'r', encoding='utf-8') as file:for line in file:process_line(line)  # 自定义的处理函数

读取/写入 Excel 文件

基本读取

读取 Excel 文件

  1. 使用 pandas
import pandas as pd# 读取 Excel 文件
df = pd.read_excel('example.xlsx', sheet_name='Sheet1')
print(df)
  1. 使用 openpyxl 库(适用于 .xlsx 文件)
from openpyxl import load_workbook# 读取 Excel 文件
wb = load_workbook('example.xlsx')
sheet = wb['Sheet1']
for row in sheet.iter_rows(values_only=True):print(row)

写入 Excel 文件

  1. 使用 pandas
import pandas as pd# 创建一个 DataFrame
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)# 写入 Excel 文件
df.to_excel('example.xlsx', sheet_name='Sheet1', index=False)
  1. 使用 openpyxl
from openpyxl import Workbook# 创建一个新的 Excel 文件
wb = Workbook()
sheet = wb.active
sheet.title = 'Sheet1'# 写入数据
sheet.append(['Name', 'Age'])
sheet.append(['Alice', 25])
sheet.append(['Bob', 30])# 保存文件
wb.save('example.xlsx')

处理复杂 Excel 文件(多个工作表)

  1. 使用 pandas 读取多个工作表
import pandas as pd# 读取 Excel 文件的所有工作表
xls = pd.ExcelFile('example.xlsx')
sheets = {}
for sheet_name in xls.sheet_names:sheets[sheet_name] = pd.read_excel(xls, sheet_name=sheet_name)print(f"Sheet: {sheet_name}")print(sheets[sheet_name])
  1. 使用 openpyxl 逐行读取
from openpyxl import load_workbook# 读取 Excel 文件
wb = load_workbook('example.xlsx')
for sheet_name in wb.sheetnames:sheet = wb[sheet_name]print(f"Sheet: {sheet_name}")for row in sheet.iter_rows(values_only=True):print(row)

处理大 Excel 文件(使用 pandaschunksize 参数)

import pandas as pd# 逐块读取大 Excel 文件
chunk_size = 1000
for chunk in pd.read_excel('large_file.xlsx', sheet_name='Sheet1', chunksize=chunk_size):process_chunk(chunk)  # 自定义的处理函数

读取/写入 JSON 文件

基本读取

基本读取 JSON 文件

  1. 使用内置的 json 模块
import json# 读取 JSON 文件
with open('example.json', 'r', encoding='utf-8') as file:data = json.load(file)print(data)

写入 JSON 文件

  1. 使用内置的 json 模块
import json# 数据
data = {'name': 'Alice', 'age': 25}# 写入 JSON 文件
with open('example.json', 'w', encoding='utf-8') as file:json.dump(data, file, ensure_ascii=False, indent=4)

读取嵌套数据:

读取嵌套json文件:

  1. 读取嵌套 JSON 数据
import json# 假设我们的 JSON 文件内容如下:
# {
#     "name": "Alice",
#     "age": 30,
#     "address": {
#         "city": "New York",
#         "zipcode": "10001"
#     },
#     "phones": ["123-456-7890", "987-654-3210"]
# }with open('example.json', 'r', encoding='utf-8') as file:data = json.load(file)print(data)# 访问嵌套数据
print(data['address']['city'])  # 输出: New York
print(data['phones'][0])  # 输出: 123-456-7890
写入嵌套 JSON 数据
import json# 嵌套数据
data = {"name": "Alice","age": 30,"address": {"city": "New York","zipcode": "10001"},"phones": ["123-456-7890", "987-654-3210"]
}# 写入 JSON 文件
with open('example.json', 'w', encoding='utf-8') as file:json.dump(data, file, ensure_ascii=False, indent=4)

复杂读取json文件

按行读取 JSON 文件在处理大文件或流式处理数据时非常有用。以下是一些方法来按行读取 JSON 文件:

方法一:逐行读取并解析每行 JSON

如果 JSON 文件每行都是一个独立的 JSON 对象,可以逐行读取并解析每行:

import json# 假设我们的 JSON 文件内容如下,每行是一个独立的 JSON 对象:
# {"name": "Alice", "age": 30}
# {"name": "Bob", "age": 25}with open('example.json', 'r', encoding='utf-8') as file:for line in file:data = json.loads(line.strip())print(data)

方法二:逐行读取并解析嵌套 JSON

如果 JSON 文件是一个包含多个对象的数组,可以使用 ijson 库逐行解析嵌套 JSON 数据:

import ijson# 假设我们的 JSON 文件内容如下:
# [
#     {"name": "Alice", "age": 30},
#     {"name": "Bob", "age": 25}
# ]with open('example.json', 'r', encoding='utf-8') as file:parser = ijson.parse(file)for prefix, event, value in parser:if prefix.endswith('.name') and event == 'string':print(f"Name: {value}")elif prefix.endswith('.age') and event == 'number':print(f"Age: {value}")

方法三:处理大 JSON 文件(分块读取)

对于非常大的 JSON 文件,可以考虑分块读取和处理:

import jsondef process_chunk(chunk):for line in chunk:data = json.loads(line.strip())print(data)chunk_size = 1000  # 每次读取1000行with open('large_file.json', 'r', encoding='utf-8') as file:chunk = []for line in file:chunk.append(line)if len(chunk) >= chunk_size:process_chunk(chunk)chunk = []if chunk:process_chunk(chunk)

方法四:使用 jsonlines

jsonlines 库专门用于处理每行一个 JSON 对象的文件:

import jsonlines# 假设我们的 JSON 文件内容如下,每行是一个独立的 JSON 对象:
# {"name": "Alice", "age": 30}
# {"name": "Bob", "age": 25}with jsonlines.open('example.json') as reader:for obj in reader:print(obj)

这些方法可以帮助你按行读取 JSON 文件,根据文件的具体结构和大小选择合适的方法来处理数据。
以上是一些常见的方法来读取和写入 txt、Excel 和 JSON 文件。每种方法都有其优缺点,选择哪种方法取决于具体的需求和使用场景。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词