Python文件读写方法详解

文件操作基础

  • Python内置了`open()`函数用于文件操作,支持读写文本和二进制文件
  • 文件操作基本步骤:打开文件 -> 操作文件 -> 关闭文件
  • 使用`with`语句可以自动管理文件关闭,避免资源泄漏
  • 打开文件

    1. 使用`open()`函数,语法:`open(file, mode='r', encoding=None)`

  • `file`:文件路径(相对或绝对)
  • `mode`:打开模式(常用'r'读、'w'写、'a'追加)
  • `encoding`:文本编码(如'utf-8')
  • 常用打开模式:
  • 'r':只读模式(默认)
  • 'w':写入模式(会清空原有内容)
  • 'a':追加模式(在文件末尾添加)
  • 'b':二进制模式(可与其它模式结合)
  • '+':读写模式(如'r+')
  • # 以只读方式打开文本文件
    file = open('example.txt', 'r', encoding='utf-8')
    
    # 以写入方式打开二进制文件
    bin_file = open('data.bin', 'wb')
    
    # 使用with语句自动管理文件
    with open('output.txt', 'w', encoding='utf-8') as f:
        # 在此代码块内操作文件
        pass  # 文件会自动关闭

    读取文件

  • 读取方法:
  • `read()`:读取整个文件
  • `readline()`:读取一行
  • `readlines()`:读取所有行到列表
  • 大文件处理技巧:
  • 逐行读取避免内存溢出
  • 使用`for`循环直接迭代文件对象
  • # 读取整个文件
    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())  # 移除行尾换行符
    
    # 读取到列表
    with open('example.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        print(lines)  # 每个元素包含换行符

    写入文件

  • 写入方法:
  • `write()`:写入字符串
  • `writelines()`:写入字符串列表
  • 写入模式差异:
  • 'w':覆盖原有内容
  • 'a':追加内容
  • 注意事项:
  • 写入操作不会自动添加换行符
  • 二进制模式需要bytes类型数据
  • # 覆盖写入文本
    with open('output.txt', 'w', encoding='utf-8') as f:
        f.write("Hello Python\n")
        f.write("文件写入操作\n")
    
    # 追加内容
    with open('output.txt', 'a', encoding='utf-8') as f:
        f.write("这是追加的内容\n")
    
    # 写入多行
    lines = ["第一行\n", "第二行\n", "第三行\n"]
    with open('output.txt', 'w', encoding='utf-8') as f:
        f.writelines(lines)
    
    # 写入二进制数据
    data = b'\x48\x65\x6c\x6c\x6f'  # "Hello"的二进制表示
    with open('binary.bin', 'wb') as f:
        f.write(data)

    文件指针操作

  • 文件指针表示当前读写位置
  • 使用`tell()`获取指针位置
  • 使用`seek()`移动指针位置
  • `seek(offset, whence)`
  • `offset`:偏移量(字节数)
  • `whence`:参考位置(0=文件头,1=当前位置,2=文件尾)
  • # 文件指针操作示例
    with open('example.txt', 'r', encoding='utf-8') as f:
        # 读取前5个字符
        print(f.read(5))
    
        # 获取当前位置
        pos = f.tell()
        print(f"当前指针位置: {pos}")
    
        # 回到文件开头
        f.seek(0)
        print("回到开头后读取:", f.read(5))
    
        # 移动到文件末尾
        f.seek(0, 2)
        print("文件大小:", f.tell())

    二进制文件处理

  • 处理非文本文件(图片、视频等)
  • 使用结构化数据模块(如`struct`)
  • 注意字节顺序和编码问题
  • # 使用struct处理二进制数据
    import struct
    
    # 写入二进制数据
    values = (1, 2.5, b'abc')  # 整数、浮点数、字节串
    with open('data.bin', 'wb') as f:
        # 打包数据:i=整数, d=双精度浮点, 3s=3字节字符串
        packed_data = struct.pack('id3s', *values)
        f.write(packed_data)
    
    # 读取二进制数据
    with open('data.bin', 'rb') as f:
        data = f.read()
        # 解包数据
        unpacked_data = struct.unpack('id3s', data)
        print("解包数据:", unpacked_data)

    文件与目录操作

  • 使用`os`和`os.path`模块
  • 常用操作:
  • 检查路径存在性
  • 创建目录
  • 获取文件信息
  • 遍历目录
  • import os
    
    # 检查文件是否存在
    if os.path.exists('example.txt'):
        print("文件存在")
    else:
        print("文件不存在")
    
    # 获取文件信息
    file_info = os.stat('example.txt')
    print("文件大小:", file_info.st_size, "字节")
    
    # 创建目录
    if not os.path.exists('new_dir'):
        os.mkdir('new_dir')
    
    # 遍历目录
    for root, dirs, files in os.walk('.'):
        print(f"目录: {root}")
        for name in dirs:
            print(f"子目录: {name}")
        for name in files:
            print(f"文件: {name}")

    异常处理

  • 处理常见文件操作异常
  • 使用try-except捕获异常
  • 常见异常类型:
  • `FileNotFoundError`:文件不存在
  • `PermissionError`:权限不足
  • `IsADirectoryError`:是目录而非文件
  • try:
        with open('nonexistent.txt', 'r', encoding='utf-8') as f:
            content = f.read()
    except FileNotFoundError:
        print("错误:文件不存在")
    except PermissionError:
        print("错误:没有足够权限")
    except IsADirectoryError:
        print("错误:指定路径是目录而非文件")
    except Exception as e:
        print(f"发生未知错误: {e}")

    总结

    Python文件操作提供了丰富而灵活的功能,通过`open()`函数可以轻松处理各种文件操作需求。关键要点包括:

    1. 始终使用`with`语句确保文件正确关闭

  • 根据需求选择合适的打开模式(r/w/a/b/+)
  • 处理文本文件时明确指定编码(通常用'utf-8')
  • 大文件处理时采用逐行读取避免内存问题
  • 二进制文件操作需注意数据类型和字节顺序
  • 6. 使用`os`模块进行高级文件系统操作

  • 完善的异常处理确保程序健壮性

掌握这些文件操作方法,可以高效处理各种文件I/O任务,为数据处理、日志记录、配置管理等场景提供坚实基础。

发表回复

后才能评论