Python基础:文件读写完全指南

0 阅读6分钟

Python基础:文件读写完全指南

掌握数据持久化的核心技能

前言

文件操作是编程中不可或缺的技能——无论是读取配置文件、处理日志、还是保存用户数据,都离不开文件的读写。Python提供了简洁而强大的文件操作接口,让开发者能够轻松地与文件系统交互。

本文将系统讲解文件读写的原理、各种模式和最佳实践,帮助你安全高效地处理文件IO任务。


一、文件操作基础

1.1 核心概念

Python使用内置的open()函数进行文件操作,它返回一个文件对象(也称为文件描述符)。现代操作系统不允许程序直接操作磁盘,所有文件操作都需要通过操作系统提供的接口来完成。

1.2 基本语法

# 基本语法
f = open(file_path, mode, encoding)

# 示例:打开一个文本文件
f = open('/path/to/file.txt', 'r')  # 'r' 表示读取模式

二、读取文件

2.1 打开文件与异常处理

如果文件不存在,会抛出FileNotFoundError异常:

try:
    f = open('/path/to/nonexistent.txt', 'r')
except FileNotFoundError as e:
    print(f"文件不存在: {e}")

2.2 读取方法汇总

方法说明适用场景
read()一次性读取全部内容小文件
read(size)按指定大小读取大文件,分块处理
readline()读取一行逐行处理
readlines()读取所有行到列表需要多行同时处理
# 一次性读取全部内容
with open('file.txt', 'r') as f:
    content = f.read()

# 按指定大小读取(适合大文件)
with open('large_file.txt', 'r') as f:
    while True:
        chunk = f.read(1024)  # 每次读取1024字节
        if not chunk:
            break
        process(chunk)

# 逐行读取
with open('file.txt', 'r') as f:
    line = f.readline()
    while line:
        print(line.strip())
        line = f.readline()

# 读取所有行到列表
with open('file.txt', 'r') as f:
    lines = f.readlines()
    for line in lines:
        print(line.strip())

2.3 安全关闭文件

使用文件后必须关闭以释放系统资源:

# 手动关闭
f = open('file.txt', 'r')
content = f.read()
f.close()  # 必须手动关闭

推荐:使用with语句自动管理

# with语句会自动关闭文件
with open('/path/to/file.txt', 'r') as f:
    content = f.read()
    # 文件会在代码块结束后自动关闭

📌 为什么用with?
with语句会在代码块执行完毕后自动关闭文件,即使发生异常也会正确处理,避免资源泄漏。


三、文件对象类型

3.1 文本文件 vs 二进制文件

模式说明示例
文本模式(默认)处理文本文件,会进行编码转换open('file.txt', 'r')
二进制模式处理图片、视频等二进制文件open('image.jpg', 'rb')

3.2 内存中的文件对象(file-like对象)

from io import StringIO, BytesIO

# 内存中的文本文件
text_stream = StringIO("一些文本内容")
content = text_stream.read()

# 内存中的二进制文件
binary_stream = BytesIO(b'\x00\x01\x02')
data = binary_stream.read()

四、处理不同编码

对于非UTF-8编码的文本文件,需要指定编码:

# 读取GBK编码文件
with open('gbk_file.txt', 'r', encoding='gbk') as f:
    content = f.read()

# 处理编码错误(忽略非法字符)
with open('file.txt', 'r', encoding='utf-8', errors='ignore') as f:
    content = f.read()

常见编码参数

编码说明
utf-8默认编码,推荐使用
gbk中文Windows系统常用
latin-1西欧语言编码

五、写入文件

5.1 写入模式

# 覆盖写入(文件不存在则创建)
with open('output.txt', 'w') as f:
    f.write('Hello, World!')

# 追加写入
with open('output.txt', 'a') as f:
    f.write('\nAnother line')

5.2 写入多行内容

lines = ['第一行', '第二行', '第三行']

# 方法1:逐行写入
with open('output.txt', 'w') as f:
    for line in lines:
        f.write(f"{line}\n")

# 方法2:使用 writelines
with open('output.txt', 'w') as f:
    f.writelines(f"{line}\n" for line in lines)

六、文件模式总结

模式描述文件指针位置
'r'读取(默认)文件开头
'w'写入(覆盖)文件开头(清空原内容)
'x'独占创建(文件存在则失败)文件开头
'a'追加文件末尾
'b'二进制模式与上述模式组合
't'文本模式(默认)与上述模式组合
'+'更新(读写)取决于使用的模式

组合示例

# 二进制读取
with open('image.jpg', 'rb') as f:
    data = f.read()

# 读写模式(覆盖)
with open('file.txt', 'w+') as f:
    f.write('Hello')
    f.seek(0)  # 移动指针到开头
    content = f.read()

# 读写模式(追加)
with open('file.txt', 'a+') as f:
    f.write('New line')
    f.seek(0)
    content = f.read()

七、最佳实践

7.1 五个核心原则

原则说明示例
使用with语句自动管理文件资源with open(...) as f:
处理大文件用迭代逐行读取,内存友好for line in f:
明确指定编码避免编码错误encoding='utf-8'
检查文件存在性避免异常os.path.exists()
处理异常捕获IO错误try...except

7.2 大文件处理示例

# 内存友好的逐行处理
with open('large_file.txt', 'r', encoding='utf-8') as f:
    for line in f:  # 不会一次性加载整个文件到内存
        process(line)  # 逐行处理

7.3 安全检查示例

import os

def safe_read_file(filepath):
    """安全读取文件内容"""
    if not os.path.exists(filepath):
        print(f"文件不存在: {filepath}")
        return None
    
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            return f.read()
    except PermissionError:
        print(f"没有权限读取文件: {filepath}")
        return None
    except Exception as e:
        print(f"读取文件时发生错误: {e}")
        return None

八、综合练习

读取系统时区文件

fpath = '/etc/timezone'  # Linux系统时区文件路径

try:
    with open(fpath, 'r', encoding='utf-8') as f:
        timezone = f.read().strip()
        print(f"系统时区: {timezone}")
except FileNotFoundError:
    print("时区文件不存在")
except PermissionError:
    print("没有权限读取时区文件")
except Exception as e:
    print(f"发生未知错误: {e}")

文件复制示例

def copy_file(src, dst):
    """复制文件,支持大文件"""
    try:
        with open(src, 'rb') as source:
            with open(dst, 'wb') as target:
                # 分块复制,避免内存占用过大
                while True:
                    chunk = source.read(8192)  # 8KB块
                    if not chunk:
                        break
                    target.write(chunk)
        print(f"文件复制成功: {src} -> {dst}")
    except Exception as e:
        print(f"复制失败: {e}")

# 使用示例
copy_file('source.jpg', 'destination.jpg')

九、总结

知识点要点
打开文件open() 返回文件对象,指定模式和编码
读取方式read()readline()readlines()、迭代器
写入方式write()writelines()
安全关闭with 语句自动管理
文件模式r/w/a/b/+ 组合使用
编码处理明确指定 encoding,处理 errors
大文件分块读取或逐行迭代
异常处理捕获 FileNotFoundErrorPermissionError

掌握文件操作是Python编程的基础技能。通过合理选择读写模式、使用with语句自动管理资源、正确处理编码和异常,你可以写出健壮高效的文件处理代码。

---💡 Python 学习不走弯路!

体系化实战路线:基础语法 · 异步Web开发 · 数据采集 · 计算机视觉 · NLP · 大模型RAG实战 —— 全在「道满PythonAI」

📚 相关推荐阅读


如果这篇文章对你有帮助,欢迎点赞、评论、收藏,你的支持是我持续分享的动力!🎉