Python文件操作案例如何读写文件

wen python案例 31

本文目录导读:

Python文件操作案例如何读写文件

  1. 基础文件读写
  2. 文件模式详解
  3. 实用案例
  4. 高级操作
  5. 常见错误处理

我来给你详细讲解Python文件操作的常见案例,从基础到进阶。

基础文件读写

写入文件

# 基本写入
with open('example.txt', 'w', encoding='utf-8') as f:
    f.write('Hello, World!\n')
    f.write('这是第二行\n')
# 写入多行
lines = ['第一行\n', '第二行\n', '第三行\n']
with open('example.txt', 'w', encoding='utf-8') as f:
    f.writelines(lines)

读取文件

# 读取整个文件
with open('example.txt', 'r', encoding='utf-8') as f:
    content = f.read()
    print(content)
# 逐行读取
with open('example.txt', 'r', encoding='utf-8') as f:
    for line in f:
        print(line.strip())  # strip()去除换行符
# 读取所有行到列表
with open('example.txt', 'r', encoding='utf-8') as f:
    lines = f.readlines()
    print(lines)

文件模式详解

# 'r' - 读取(默认)
# 'w' - 写入(覆盖)
# 'a' - 追加
# 'x' - 创建新文件(如果已存在则报错)
# 'b' - 二进制模式
# 't' - 文本模式(默认)
# '+' - 读写模式
# 追加写入
with open('log.txt', 'a', encoding='utf-8') as f:
    f.write('新增的日志内容\n')
# 二进制模式读取图片
with open('image.jpg', 'rb') as f:
    data = f.read()
    print(f"图片大小: {len(data)} 字节")
# 读写模式
with open('data.txt', 'r+', encoding='utf-8') as f:
    content = f.read()
    f.seek(0)  # 回到文件开头
    f.write('新内容\n' + content)

实用案例

案例1:复制文件

def copy_file(source, destination):
    """复制文件"""
    with open(source, 'rb') as src:
        with open(destination, 'wb') as dst:
            # 分块读取大文件
            while True:
                chunk = src.read(8192)  # 8KB块
                if not chunk:
                    break
                dst.write(chunk)
    print(f"文件 {source} 已复制到 {destination}")
# 使用示例
copy_file('source.txt', 'destination.txt')

案例2: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]}")

案例3:配置文件读写

import configparser
# 写入配置
config = configparser.ConfigParser()
config['DEFAULT'] = {
    'ServerAliveInterval': '45',
    'Compression': 'yes',
    'CompressionLevel': '9'
}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
config['topsecret.server.com']['Host Port'] = '50022'
config['topsecret.server.com']['ForwardX11'] = 'no'
with open('config.ini', 'w', encoding='utf-8') as f:
    config.write(f)
# 读取配置
config = configparser.ConfigParser()
config.read('config.ini', encoding='utf-8')
print(config['DEFAULT']['Compression'])
print(config['bitbucket.org']['User'])

案例4:日志文件处理

import os
from datetime import datetime
def write_log(message, log_file='app.log'):
    """写入日志,自动添加时间戳"""
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    log_entry = f'[{timestamp}] {message}\n'
    with open(log_file, 'a', encoding='utf-8') as f:
        f.write(log_entry)
def read_logs(line_count=10):
    """读取最近N行日志"""
    with open('app.log', 'r', encoding='utf-8') as f:
        lines = f.readlines()
    # 获取最后N行
    recent_lines = lines[-line_count:]
    for line in recent_lines:
        print(line.strip())
# 使用示例
write_log('程序启动')
write_log('用户登录成功')
write_log('数据更新完成')
read_logs(3)

高级操作

文件指针操作

with open('example.txt', 'r+', encoding='utf-8') as f:
    # 获取当前位置
    pos = f.tell()
    print(f"当前位置: {pos}")
    # 读取10个字符
    content = f.read(10)
    print(f"读取内容: {content}")
    # 移动到文件开头
    f.seek(0)
    # 从当前位置向前移动10个字符
    f.seek(10, 1)  # 1表示相对当前位置
    # 从文件末尾向前移动20个字符
    f.seek(-20, 2)  # 2表示相对文件末尾

临时文件处理

import tempfile
# 创建临时文件
with tempfile.TemporaryFile(mode='w+t') as temp:
    temp.write('临时数据')
    temp.seek(0)
    print(temp.read())
# 创建临时目录
with tempfile.TemporaryDirectory() as temp_dir:
    temp_file = os.path.join(temp_dir, 'test.txt')
    with open(temp_file, 'w') as f:
        f.write('临时文件')
    print(f"临时目录: {temp_dir}")

常见错误处理

def safe_file_read(filename):
    """安全的文件读取函数"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return f.read()
    except FileNotFoundError:
        print(f"错误: 文件 {filename} 不存在")
        return None
    except PermissionError:
        print(f"错误: 没有权限读取文件 {filename}")
        return None
    except UnicodeDecodeError:
        print(f"错误: 无法解码文件 {filename},请使用正确的编码")
        return None
# 使用示例
content = safe_file_read('example.txt')
if content:
    print(content)

这些案例涵盖了Python文件操作的主要场景,根据实际需求选择合适的读写模式和方法,注意正确处理文件编码和异常情况。

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