Python进阶:文件读写操作详解

道友今天开始进阶练习,来吧

文件读写是Python编程中非常重要的技能,掌握这些操作可以帮助你处理各种数据存储和交换任务。下面我将详细介绍Python中的文件读写操作。

一、基本文件操作

1. 打开文件

使用open()函数打开文件,基本语法:

file = open(filename, mode='r', encoding=None)

常用模式:

  • 'r' - 读取(默认)
  • 'w' - 写入(会覆盖已有文件)
  • 'a' - 追加
  • 'x' - 独占创建(如果文件已存在则失败)
  • 'b' - 二进制模式
  • 't' - 文本模式(默认)
  • '+' - 更新(可读可写)

2. 读取文件内容

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

# 逐行读取
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()

3. 写入文件

# 写入字符串
with open('output.txt', 'w') as f:
    f.write("Hello, World!\n")

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

二、高级文件操作

1. 上下文管理器(推荐)

使用with语句可以自动管理文件资源,确保文件正确关闭:

with open('file.txt', 'r') as f:
    data = f.read()
# 离开with块后,文件自动关闭

2. 二进制文件操作

处理图片、视频等二进制文件:

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

# 写入二进制文件
with open('copy.jpg', 'wb') as f:
    f.write(binary_data)

3. 文件指针操作

with open('file.txt', 'r+') as f:
    # 获取当前位置
    pos = f.tell()
    
    # 移动到文件开头
    f.seek(0)
    
    # 移动到文件末尾
    f.seek(0, 2)
    
    # 从当前位置向后移动5个字节
    f.seek(5, 1)

4. 缓冲与刷新

# 立即刷新缓冲区
with open('file.txt', 'w') as f:
    f.write("Some data")
    f.flush()  # 立即写入磁盘
    
# 设置缓冲区大小
with open('file.txt', 'w', buffering=1) as f:  # 行缓冲
    f.write("Buffered output\n")

三、常见文件格式处理

1. CSV文件

import csv

# 读取CSV
with open('data.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

# 写入CSV
data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(data)

2. JSON文件

import json

# 读取JSON
with open('data.json', 'r') as f:
    data = json.load(f)

# 写入JSON
data = {'name': 'Alice', 'age': 25, 'skills': ['Python', 'SQL']}
with open('output.json', 'w') as f:
    json.dump(data, f, indent=4)

3. 配置文件(configparser)

from configparser import ConfigParser

config = ConfigParser()
config.read('config.ini')

# 获取配置
db_host = config.get('Database', 'host')
db_port = config.getint('Database', 'port')

# 修改配置
config.set('Database', 'port', '5433')
with open('config.ini', 'w') as f:
    config.write(f)

四、文件系统操作

import os
import shutil

# 检查文件/目录是否存在
os.path.exists('path/to/file')

# 获取文件大小
os.path.getsize('file.txt')

# 重命名文件
os.rename('old.txt', 'new.txt')

# 删除文件
os.remove('file.txt')

# 创建目录
os.mkdir('new_dir')

# 递归创建目录
os.makedirs('path/to/new/dir')

# 删除目录
os.rmdir('empty_dir')  # 只能删除空目录
shutil.rmtree('dir')   # 删除目录及其内容

# 遍历目录
for root, dirs, files in os.walk('path'):
    print(f"当前目录: {root}")
    print(f"子目录: {dirs}")
    print(f"文件: {files}")

五、高级技巧

1. 内存映射文件(处理大文件)

import mmap

with open('large_file.bin', 'r+b') as f:
    # 创建内存映射
    mm = mmap.mmap(f.fileno(), 0)
    
    # 像操作字符串一样操作文件
    print(mm[:100])  # 读取前100字节
    
    # 修改内容
    mm[0:5] = b'HELLO'
    
    # 关闭映射
    mm.close()

2. 临时文件

from tempfile import TemporaryFile, NamedTemporaryFile

# 创建临时文件(不显示在文件系统中)
with TemporaryFile('w+t') as f:
    f.write('临时数据')
    f.seek(0)
    print(f.read())

# 创建有名临时文件
with NamedTemporaryFile('w+t', delete=False) as f:
    print(f"临时文件路径: {f.name}")
    f.write('更多临时数据')

3. 文件压缩与解压

import gzip
import zipfile

# Gzip压缩
with gzip.open('file.txt.gz', 'wt') as f:
    f.write("压缩的文本内容")

# Zip压缩
with zipfile.ZipFile('archive.zip', 'w') as z:
    z.write('file1.txt')
    z.write('file2.txt')

# Zip解压
with zipfile.ZipFile('archive.zip', 'r') as z:
    z.extractall('extracted_files')

六、最佳实践

  1. 始终使用with语句管理文件资源
  2. 处理文本文件时明确指定编码(推荐UTF-8)
  3. 处理大文件时使用迭代或内存映射
  4. 对关键文件操作添加异常处理
  5. 使用os.path进行路径操作,而非字符串拼接
try:
    with open('important.txt', 'r', encoding='utf-8') as f:
        content = f.read()
except FileNotFoundError:
    print("文件不存在")
except UnicodeDecodeError:
    print("文件编码错误")
except IOError as e:
    print(f"IO错误: {e}")

学废了吗?

原文链接:,转发请注明来源!