Skip to content

Python 文件操作

文件操作是编程中常见的任务,Python 提供了丰富的文件操作功能。本章节将详细介绍 Python 中的文件读写操作。

打开文件

在 Python 中,使用 open() 函数打开文件。

基本语法

python
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

参数说明

  • file:文件路径(字符串)
  • mode:打开模式(字符串)
  • buffering:缓冲策略
  • encoding:编码方式(如 'utf-8')
  • errors:编码错误处理方式
  • newline:换行符处理方式
  • closefd:是否关闭文件描述符
  • opener:自定义打开器

打开模式

模式描述
'r'只读模式(默认)
'w'写入模式,会覆盖原有内容
'a'追加模式,在文件末尾添加内容
'x'独占创建模式,文件不存在时创建
'b'二进制模式
't'文本模式(默认)
'+'读写模式

常见组合模式

模式描述
'r''rt'只读文本模式
'w''wt'写入文本模式
'a''at'追加文本模式
'rb'只读二进制模式
'wb'写入二进制模式
'ab'追加二进制模式
'r+'读写文本模式
'w+'读写文本模式(会覆盖原有内容)
'a+'读写文本模式(在文件末尾添加内容)

关闭文件

使用 close() 方法关闭文件,释放系统资源。

基本语法

python
file.close()

示例

python
# 打开和关闭文件
f = open('example.txt', 'w')
try:
    f.write('Hello, World!')
finally:
    f.close()  # 确保文件被关闭

使用 with 语句

with 语句可以自动管理文件的关闭,即使发生异常也会正确关闭文件。

python
# 使用 with 语句
with open('example.txt', 'w') as f:
    f.write('Hello, World!')
# 退出 with 块时,文件会自动关闭

读取文件

读取整个文件

python
# 读取整个文件
with open('example.txt', 'r') as f:
    content = f.read()
    print(content)

逐行读取

python
# 逐行读取
with open('example.txt', 'r') as f:
    for line in f:
        print(line.strip())  # strip() 去除换行符和空白

# 另一种方式
with open('example.txt', 'r') as f:
    lines = f.readlines()
    for line in lines:
        print(line.strip())

读取指定字节

python
# 读取指定字节
with open('example.txt', 'r') as f:
    content = f.read(5)  # 读取前 5 个字符
    print(content)

写入文件

写入字符串

python
# 写入字符串
with open('example.txt', 'w') as f:
    f.write('Hello, World!\n')
    f.write('How are you?')

写入多行

python
# 写入多行
lines = ['Line 1\n', 'Line 2\n', 'Line 3']
with open('example.txt', 'w') as f:
    f.writelines(lines)

# 另一种方式
with open('example.txt', 'w') as f:
    for line in lines:
        f.write(line)

追加内容

python
# 追加内容
with open('example.txt', 'a') as f:
    f.write('\nAppended line')

文件指针操作

文件指针用于标记当前读写位置。

获取当前位置

python
# 获取当前位置
with open('example.txt', 'r') as f:
    print(f.tell())  # 输出:0(文件开头)
    f.read(5)
    print(f.tell())  # 输出:5(当前位置)

移动文件指针

python
# 移动文件指针
with open('example.txt', 'r') as f:
    print(f.read(5))  # 读取前 5 个字符
    f.seek(0)  # 移动到文件开头
    print(f.read(5))  # 再次读取前 5 个字符
    f.seek(2, 0)  # 从文件开头移动 2 个字节
    print(f.read(3))  # 读取 3 个字符
    f.seek(1, 1)  # 从当前位置移动 1 个字节
    print(f.read(2))  # 读取 2 个字符
    f.seek(-5, 2)  # 从文件末尾向前移动 5 个字节
    print(f.read())  # 读取剩余内容

参数说明

  • offset:偏移量
  • whence:基准位置(0:文件开头,1:当前位置,2:文件末尾)

二进制文件操作

读取二进制文件

python
# 读取二进制文件
with open('example.bin', 'rb') as f:
    content = f.read()
    print(content)

写入二进制文件

python
# 写入二进制文件
data = b'Hello, Binary!'
with open('example.bin', 'wb') as f:
    f.write(data)

文件操作的异常处理

在文件操作中,可能会遇到各种异常,如文件不存在、权限不足等。

基本异常处理

python
# 基本异常处理
try:
    with open('nonexistent.txt', 'r') as f:
        content = f.read()
    print(content)
except FileNotFoundError:
    print('文件不存在')
except PermissionError:
    print('权限不足')
except Exception as e:
    print(f'发生错误:{e}')

高级异常处理

python
# 高级异常处理
try:
    f = open('example.txt', 'r')
except FileNotFoundError:
    print('文件不存在,创建新文件')
    f = open('example.txt', 'w')
    f.write('Initial content')
    f.close()
    f = open('example.txt', 'r')
else:
    print('文件打开成功')
finally:
    if 'f' in locals() and not f.closed:
        f.close()
        print('文件已关闭')

文件和目录操作

Python 的 osos.path 模块提供了文件和目录操作功能。

导入模块

python
import os
import os.path

文件操作

python
# 文件操作

# 检查文件是否存在
print(f'文件是否存在:{os.path.exists("example.txt")}')

# 检查是否为文件
print(f'是否为文件:{os.path.isfile("example.txt")}')

# 检查是否为目录
print(f'是否为目录:{os.path.isdir("example.txt")}')

# 获取文件大小
print(f'文件大小:{os.path.getsize("example.txt")} 字节')

# 获取文件修改时间
import time
mod_time = os.path.getmtime("example.txt")
print(f'文件修改时间:{time.ctime(mod_time)}')

# 重命名文件
os.rename("example.txt", "new_example.txt")
print('文件已重命名')

# 复制文件
import shutil
shutil.copy("new_example.txt", "copy_example.txt")
print('文件已复制')

# 删除文件
os.remove("copy_example.txt")
print('文件已删除')

# 恢复文件名
os.rename("new_example.txt", "example.txt")
print('文件名已恢复')

目录操作

python
# 目录操作

# 创建目录
os.makedirs("test_dir", exist_ok=True)
print('目录已创建')

# 切换目录
os.chdir("test_dir")
print(f'当前目录:{os.getcwd()}')

# 创建文件
with open('test.txt', 'w') as f:
    f.write('Test content')
print('文件已创建')

# 列出目录内容
print(f'目录内容:{os.listdir(".")}')

# 切换回上级目录
os.chdir("..")
print(f'当前目录:{os.getcwd()}')

# 删除目录及其内容
shutil.rmtree("test_dir")
print('目录已删除')

路径操作

python
# 路径操作

# 获取绝对路径
print(f'绝对路径:{os.path.abspath("example.txt")}')

# 获取目录名
print(f'目录名:{os.path.dirname(os.path.abspath("example.txt"))}')

# 获取文件名
print(f'文件名:{os.path.basename("example.txt")}')

# 分割路径
print(f'路径分割:{os.path.split(os.path.abspath("example.txt"))}')

# 连接路径
print(f'路径连接:{os.path.join(os.getcwd(), "subdir", "file.txt")}')

# 检查路径是否存在
print(f'路径是否存在:{os.path.exists(os.path.join(os.getcwd(), "example.txt"))}')

临时文件和目录

Python 的 tempfile 模块提供了创建临时文件和目录的功能。

创建临时文件

python
# 创建临时文件
import tempfile

# 方法 1:使用 NamedTemporaryFile
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
    f.write('Temporary content')
    temp_file_name = f.name
    print(f'临时文件名:{temp_file_name}')

# 读取临时文件
with open(temp_file_name, 'r') as f:
    print(f'临时文件内容:{f.read()}')

# 删除临时文件
os.unlink(temp_file_name)
print('临时文件已删除')

# 方法 2:使用 TemporaryFile(自动删除)
with tempfile.TemporaryFile(mode='w+') as f:
    f.write('Temporary content')
    f.seek(0)
    print(f'临时文件内容:{f.read()}')
# 退出 with 块时,临时文件会自动删除

创建临时目录

python
# 创建临时目录
with tempfile.TemporaryDirectory() as temp_dir:
    print(f'临时目录:{temp_dir}')
    # 在临时目录中创建文件
    temp_file = os.path.join(temp_dir, 'test.txt')
    with open(temp_file, 'w') as f:
        f.write('Test content')
    # 读取文件
    with open(temp_file, 'r') as f:
        print(f'文件内容:{f.read()}')
# 退出 with 块时,临时目录会自动删除

文件编码

在处理文本文件时,编码是一个重要的考虑因素。

指定编码

python
# 指定编码
with open('example.txt', 'w', encoding='utf-8') as f:
    f.write('你好,世界!')

with open('example.txt', 'r', encoding='utf-8') as f:
    content = f.read()
    print(content)

处理编码错误

python
# 处理编码错误
with open('example.txt', 'r', encoding='utf-8', errors='replace') as f:
    content = f.read()
    print(content)

# 其他错误处理方式:'ignore', 'strict'

高级文件操作

大文件处理

处理大文件时,应该逐行读取,避免一次性加载整个文件到内存。

python
# 处理大文件
def process_large_file(file_path):
    """逐行处理大文件"""
    with open(file_path, 'r') as f:
        for line_number, line in enumerate(f, 1):
            # 处理每一行
            print(f'Line {line_number}: {line.strip()}')
            # 这里可以添加具体的处理逻辑

# 示例:创建一个大文件
with open('large_file.txt', 'w') as f:
    for i in range(1000):
        f.write(f'Line {i+1}: This is a test line\n')

# 处理大文件
process_large_file('large_file.txt')

# 删除测试文件
os.remove('large_file.txt')

文件读写性能优化

python
# 文件读写性能优化

# 方法 1:使用缓冲
with open('example.txt', 'w', buffering=1024*1024) as f:  # 1MB 缓冲
    for i in range(10000):
        f.write(f'Line {i+1}\n')

# 方法 2:批量写入
lines = [f'Line {i+1}\n' for i in range(10000)]
with open('example.txt', 'w') as f:
    f.writelines(lines)

# 方法 3:使用二进制模式(对于非文本文件)
data = b'Hello' * 10000
with open('binary_file.bin', 'wb') as f:
    f.write(data)

总结

Python 提供了丰富的文件操作功能,包括:

  1. 文件打开和关闭:使用 open() 函数和 with 语句
  2. 文件读取read(), readline(), readlines() 方法
  3. 文件写入write(), writelines() 方法
  4. 文件指针操作tell(), seek() 方法
  5. 文件和目录操作:使用 osos.path 模块
  6. 临时文件和目录:使用 tempfile 模块
  7. 文件编码处理:指定编码和错误处理方式
  8. 大文件处理:逐行读取,避免内存溢出
  9. 性能优化:使用缓冲、批量写入等方法

掌握这些文件操作技巧,对于处理各种文件相关任务非常重要。