Python案例中如何处理文件读写?

wen python案例 2

本文目录导读:

Python案例中如何处理文件读写?

  1. 基础文件操作
  2. 读取文件内容
  3. 写入文件内容
  4. 实用案例
  5. 高级技巧
  6. 最佳实践

在Python中处理文件读写是基础且重要的技能,下面我将从基础到进阶,系统地介绍各种文件读写方法。

基础文件操作

打开和关闭文件

# 基本方式
file = open('example.txt', 'r', encoding='utf-8')
content = file.read()
file.close()  # 必须手动关闭
# 推荐方式:使用with语句(自动关闭文件)
with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
# 文件在此处自动关闭

文件打开模式

模式 说明
'r' 只读(默认)
'w' 写入(覆盖已有内容)
'a' 追加(在文件末尾添加)
'x' 创建新文件(已存在则报错)
'b' 二进制模式(如 'rb'
't' 文本模式(默认)
读写模式(如 'r+'

读取文件内容

三种读取方法

# 方式1:read() - 一次性读取全部内容
with open('example.txt', 'r', encoding='utf-8') as f:
    content = f.read()
    print(content)
# 方式2:readline() - 逐行读取
with open('example.txt', 'r', encoding='utf-8') as f:
    line = f.readline()
    while line:
        print(line.strip())  # strip()去除换行符
        line = f.readline()
# 方式3:readlines() - 读取所有行到列表
with open('example.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    for line in lines:
        print(line.strip())

推荐读取方式

# 最常用的逐行读取方式(内存友好)
with open('example.txt', 'r', encoding='utf-8') as f:
    for line in f:  # 文件对象是可迭代的
        print(line.strip())
# 读取指定字节数
with open('large_file.txt', 'r', encoding='utf-8') as f:
    chunk_size = 1024  # 每次读取1KB
    while True:
        chunk = f.read(chunk_size)
        if not chunk:  # 读取完毕
            break
        process(chunk)  # 处理数据块

写入文件内容

基本写入

# 写入字符串
with open('output.txt', 'w', encoding='utf-8') as f:
    f.write('Hello, World!\n')
    f.write('第二行内容\n')
# 写入多行
lines = ['第一行', '第二行', '第三行']
with open('output.txt', 'w', encoding='utf-8') as f:
    for line in lines:
        f.write(line + '\n')

使用writelines()

# writelines()不会自动添加换行符
lines = ['line1\n', 'line2\n', 'line3\n']
with open('output.txt', 'w', encoding='utf-8') as f:
    f.writelines(lines)
# 或者手动添加换行符
lines = ['line1', 'line2', 'line3']
with open('output.txt', 'w', encoding='utf-8') as f:
    f.writelines(line + '\n' for line in lines)

实用案例

案例1:文件复制

def copy_file(source, destination):
    """复制文件"""
    try:
        with open(source, 'rb') as src, open(destination, 'wb') as dst:
            for chunk in iter(lambda: src.read(4096), b''):
                dst.write(chunk)
        print(f"成功从 {source} 复制到 {destination}")
    except FileNotFoundError:
        print(f"源文件 {source} 不存在")
    except PermissionError:
        print("权限不足")
# 使用示例
copy_file('source.txt', 'destination.txt')

案例2:日志文件追加

import datetime
def write_log(message, log_file='app.log'):
    """写入日志"""
    timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    with open(log_file, 'a', encoding='utf-8') as f:
        f.write(f'[{timestamp}] {message}\n')
# 使用示例
write_log('用户登录成功')
write_log('系统运行正常')

案例3:配置文件读写

import json
# 写入JSON配置文件
config = {
    'database': {
        'host': 'localhost',
        'port': 3306,
        'user': 'admin',
        'password': 'secret'
    },
    'debug': True,
    'max_connections': 100
}
with open('config.json', 'w', encoding='utf-8') as f:
    json.dump(config, f, indent=4, ensure_ascii=False)
# 读取JSON配置文件
with open('config.json', 'r', encoding='utf-8') as f:
    loaded_config = json.load(f)
    print(loaded_config['database']['host'])

案例4:CSV文件处理

import csv
# 写入CSV
data = [
    ['姓名', '年龄', '城市'],
    ['张三', 25, '北京'],
    ['李四', 30, '上海'],
    ['王五', 28, '广州']
]
with open('users.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(data)
# 读取CSV
with open('users.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(f'{row[0]}: {row[1]}岁, 来自{row[2]}')

案例5:错误处理机制

def safe_read_file(file_path):
    """安全的文件读取函数"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return f.read()
    except FileNotFoundError:
        print(f"错误:文件 {file_path} 未找到")
        return None
    except PermissionError:
        print(f"错误:没有权限读取 {file_path}")
        return None
    except UnicodeDecodeError:
        print(f"错误:文件编码不正确,尝试二进制模式")
        try:
            with open(file_path, 'rb') as f:
                return f.read().decode('gbk')  # 尝试其他编码
        except:
            return None
    except Exception as e:
        print(f"未知错误:{e}")
        return None

高级技巧

处理大文件

def process_large_file(file_path, chunk_size=1024*1024):
    """处理大文件时使用迭代器"""
    with open(file_path, 'rb') as f:
        while True:
            chunk = f.read(chunk_size)
            if not chunk:
                break
            yield chunk
# 使用示例
for chunk in process_large_file('large_file.bin'):
    # 处理每个chunk
    pass

临时文件处理

import tempfile
# 创建临时文件
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as tmp:
    tmp.write('临时数据')
    tmp_path = tmp.name
print(f'临时文件创建在: {tmp_path}')
# 读取临时文件
with open(tmp_path, 'r') as f:
    print(f.read())
# 最后手动删除
import os
os.unlink(tmp_path)

文件指针操作

with open('example.txt', 'r', encoding='utf-8') as f:
    print(f.tell())  # 当前指针位置:0
    f.read(5)  # 读取5个字符
    print(f.tell())  # 当前指针位置:5
    f.seek(0)  # 回到文件开头
    print(f.read(5))  # 重新读取前5个字符
    f.seek(10, 0)  # 从开头偏移10个字符
    f.seek(5, 1)   # 从当前位置偏移5个字符
    f.seek(-5, 2)  # 从文件末尾向前偏移5个字符

最佳实践

  1. 始终使用with语句:确保文件自动关闭
  2. 指定编码:通常使用utf-8编码
  3. 处理异常:考虑文件不存在、权限问题等情况
  4. 使用二进制模式处理非文本文件:如图片、视频等
  5. 对大文件使用流式处理:避免内存溢出
  6. 使用上下文管理器:处理需要清理的资源

Python的文件读写操作非常灵活,掌握了这些基础方法后,你可以轻松应对大部分文件处理需求,在实际开发中,建议:

  • 优先使用with语句
  • 注意编码问题
  • 做好异常处理
  • 根据文件大小选择合适的读取方式

这样就能写出健壮、高效的文件处理代码。

抱歉,评论功能暂时关闭!