06.python中文件的读写

Python中文件的读写详解

  1. 文件操作基础
  2. 文件的打开模式
  3. 文件的读取操作
  4. 文件的写入操作
  5. 使用with语句管理文件
  6. 文件路径处理
  7. 文件编码问题
  8. 异常处理
  9. 实际应用示例
  10. 常见问题与注意事项

1. 文件操作基础

1.1 什么是文件操作

文件操作是指程序与计算机文件系统进行交互的过程,包括:

  • 读取文件:从文件中获取数据
  • 写入文件:向文件中保存数据
  • 追加数据:在文件末尾添加新数据
  • 修改文件:更新文件中的内容

1.2 文件操作的基本流程

文件操作通常遵循以下三个步骤:

  1. 打开文件:使用open()函数打开文件
  2. 操作文件:读取或写入数据
  3. 关闭文件:使用close()方法关闭文件

1.3 最简单的文件操作示例

# 示例1:读取文件的基本步骤
# 第一步:打开文件
file = open('test.txt', 'r', encoding='utf-8')

# 第二步:读取文件内容
content = file.read()
print(content)

# 第三步:关闭文件
file.close()

2. 文件的打开模式

2.1 open()函数详解

open()函数是Python中用于打开文件的内置函数,其基本语法为:

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

主要参数说明:

  • file:文件路径(字符串)
  • mode:打开模式(字符串)
  • encoding:文件编码(字符串,如’utf-8’)

2.2 文本模式(Text Mode)

2.2.1 ‘r’ – 只读模式(默认)

# 示例2:只读模式打开文件
file = open('example.txt', 'r', encoding='utf-8')
content = file.read()
print(content)
file.close()

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

2.2.2 ‘w’ – 写入模式(覆盖)

# 示例3:写入模式(会覆盖原文件内容)
file = open('example.txt', 'w', encoding='utf-8')
file.write('这是第一行内容n')
file.write('这是第二行内容n')
file.close()

# 注意:如果文件不存在,会自动创建;如果文件存在,原有内容会被清空

2.2.3 ‘a’ – 追加模式

# 示例4:追加模式(在文件末尾添加内容)
file = open('example.txt', 'a', encoding='utf-8')
file.write('这是追加的内容n')
file.close()

# 注意:如果文件不存在,会自动创建;如果文件存在,新内容会添加到文件末尾

2.2.4 ‘r+’ – 读写模式

# 示例5:读写模式(可以同时读取和写入)
file = open('example.txt', 'r+', encoding='utf-8')
content = file.read()  # 先读取
print('读取的内容:', content)
file.write('新添加的内容n')  # 再写入
file.close()

2.2.5 ‘w+’ – 读写模式(覆盖)

# 示例6:读写模式(覆盖原文件)
file = open('example.txt', 'w+', encoding='utf-8')
file.write('新内容n')  # 先写入
file.seek(0)  # 将文件指针移到开头
content = file.read()  # 再读取
print(content)
file.close()

2.2.6 ‘a+’ – 追加读写模式

# 示例7:追加读写模式
file = open('example.txt', 'a+', encoding='utf-8')
file.write('追加的内容n')  # 写入
file.seek(0)  # 移到开头
content = file.read()  # 读取
print(content)
file.close()

2.3 二进制模式(Binary Mode)

二进制模式用于处理非文本文件,如图片、视频、音频等。

2.3.1 ‘rb’ – 二进制只读

# 示例8:读取二进制文件(如图片)
file = open('image.jpg', 'rb')
data = file.read()
file.close()

# 注意:二进制模式不需要指定encoding参数

2.3.2 ‘wb’ – 二进制写入

# 示例9:写入二进制文件
file = open('copy.jpg', 'wb')
file.write(data)  # data是二进制数据
file.close()

2.3.3 ‘ab’ – 二进制追加

# 示例10:二进制追加模式
file = open('data.bin', 'ab')
file.write(b'x00x01x02x03')  # 写入二进制数据
file.close()

2.4 模式总结表

模式 说明 文件不存在 文件存在
‘r’ 只读 报错 正常读取
‘w’ 写入(覆盖) 创建 清空后写入
‘a’ 追加 创建 末尾追加
‘r+’ 读写 报错 可读可写
‘w+’ 读写(覆盖) 创建 清空后读写
‘a+’ 追加读写 创建 末尾追加,可读
‘rb’ 二进制只读 报错 正常读取
‘wb’ 二进制写入 创建 清空后写入
‘ab’ 二进制追加 创建 末尾追加

3. 文件的读取操作

3.1 read()方法 – 读取全部内容

# 示例11:读取文件的全部内容
file = open('example.txt', 'r', encoding='utf-8')
content = file.read()  # 读取所有内容
print(content)
file.close()

# read()可以指定读取的字符数
file = open('example.txt', 'r', encoding='utf-8')
first_10_chars = file.read(10)  # 只读取前10个字符
print(first_10_chars)
file.close()

3.2 readline()方法 – 读取一行

# 示例12:逐行读取文件
file = open('example.txt', 'r', encoding='utf-8')

# 读取第一行
line1 = file.readline()
print('第一行:', line1)

# 读取第二行
line2 = file.readline()
print('第二行:', line2)

file.close()

# 注意:readline()会保留行尾的换行符n

3.3 readlines()方法 – 读取所有行

# 示例13:读取所有行,返回列表
file = open('example.txt', 'r', encoding='utf-8')
lines = file.readlines()  # 返回包含所有行的列表
print(lines)
file.close()

# 输出示例:['第一行n', '第二行n', '第三行n']

3.4 遍历文件对象

# 示例14:直接遍历文件对象(推荐方式)
file = open('example.txt', 'r', encoding='utf-8')

for line in file:
    print(line.strip())  # strip()去除行尾的换行符和空格

file.close()

# 这种方式内存效率高,适合大文件

3.5 读取大文件的技巧

# 示例15:分块读取大文件
file = open('large_file.txt', 'r', encoding='utf-8')

# 方法1:每次读取指定大小的内容
chunk_size = 1024  # 每次读取1024个字符
while True:
    chunk = file.read(chunk_size)
    if not chunk:  # 如果读取到空字符串,说明文件已读完
        break
    print(chunk)

file.close()

# 方法2:逐行读取大文件(内存友好)
file = open('large_file.txt', 'r', encoding='utf-8')
for line in file:
    process(line)  # 处理每一行
file.close()

3.6 文件指针操作

# 示例16:文件指针操作
file = open('example.txt', 'r', encoding='utf-8')

# tell():获取当前文件指针位置
position = file.tell()
print('当前位置:', position)

# read(10):读取10个字符,指针会移动
content = file.read(10)
print('读取的内容:', content)
print('新位置:', file.tell())

# seek(offset, whence):移动文件指针
# whence: 0-文件开头,1-当前位置,2-文件末尾
file.seek(0)  # 回到文件开头
print('回到开头后的位置:', file.tell())

file.seek(0, 2)  # 移动到文件末尾
print('文件末尾位置:', file.tell())

file.close()

4. 文件的写入操作

4.1 write()方法 – 写入字符串

# 示例17:使用write()写入内容
file = open('output.txt', 'w', encoding='utf-8')

# 写入字符串
file.write('这是第一行内容')
file.write('这是第二行内容')  # 注意:不会自动换行

# 手动添加换行符
file.write('n这是第三行内容n')
file.write('这是第四行内容n')

file.close()

4.2 writelines()方法 – 写入多行

# 示例18:使用writelines()写入多行
file = open('output.txt', 'w', encoding='utf-8')

# writelines()接受一个字符串列表
lines = ['第一行n', '第二行n', '第三行n']
file.writelines(lines)

file.close()

# 注意:writelines()不会自动添加换行符,需要手动添加n

4.3 写入不同类型的数据

# 示例19:写入不同类型的数据
file = open('data.txt', 'w', encoding='utf-8')

# 写入字符串
file.write('字符串内容n')

# 写入数字(需要转换为字符串)
number = 123
file.write(str(number) + 'n')

# 写入列表内容
my_list = ['apple', 'banana', 'orange']
for item in my_list:
    file.write(item + 'n')

file.close()

4.4 格式化写入

# 示例20:格式化写入文件
file = open('formatted.txt', 'w', encoding='utf-8')

name = '张三'
age = 25
score = 95.5

# 使用f-string格式化
file.write(f'姓名:{name}n')
file.write(f'年龄:{age}n')
file.write(f'分数:{score}n')

# 使用format()方法
file.write('姓名:{}n'.format(name))
file.write('年龄:{}n'.format(age))

# 使用%格式化
file.write('分数:%.2fn' % score)

file.close()

4.5 追加写入示例

# 示例21:追加模式写入
# 假设example.txt已经存在,内容为:
# 原有第一行
# 原有第二行

file = open('example.txt', 'a', encoding='utf-8')
file.write('新增的第一行n')
file.write('新增的第二行n')
file.close()

# 文件内容变为:
# 原有第一行
# 原有第二行
# 新增的第一行
# 新增的第二行

5. 使用with语句管理文件

5.1 为什么使用with语句

使用with语句可以自动管理文件的打开和关闭,即使发生异常也能确保文件被正确关闭。

5.2 with语句的基本用法

# 示例22:使用with语句读取文件
with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)
# 文件会自动关闭,不需要手动调用close()

# 示例23:使用with语句写入文件
with open('output.txt', 'w', encoding='utf-8') as file:
    file.write('使用with语句写入的内容n')
# 文件会自动关闭

5.3 with语句的优势

# 示例24:对比传统方式和with语句

# 传统方式(容易忘记关闭文件)
file = open('example.txt', 'r', encoding='utf-8')
content = file.read()
# 如果这里发生异常,文件可能不会被关闭
file.close()

# with语句(自动关闭,即使发生异常)
try:
    with open('example.txt', 'r', encoding='utf-8') as file:
        content = file.read()
        # 即使这里发生异常,文件也会被自动关闭
except Exception as e:
    print('发生错误:', e)
# 文件已经自动关闭

5.4 同时打开多个文件

# 示例25:使用with语句同时打开多个文件
with open('input.txt', 'r', encoding='utf-8') as input_file, 
     open('output.txt', 'w', encoding='utf-8') as output_file:
    content = input_file.read()
    output_file.write(content)
# 两个文件都会自动关闭

5.5 实际应用示例

# 示例26:使用with语句复制文件
with open('source.txt', 'r', encoding='utf-8') as source:
    with open('copy.txt', 'w', encoding='utf-8') as target:
        content = source.read()
        target.write(content)
print('文件复制完成')

6. 文件路径处理

6.1 相对路径和绝对路径

# 示例27:相对路径和绝对路径
import os

# 相对路径(相对于当前工作目录)
file1 = open('data.txt', 'r', encoding='utf-8')

# 相对路径(子目录)
file2 = open('folder/data.txt', 'r', encoding='utf-8')

# 相对路径(上级目录)
file3 = open('../data.txt', 'r', encoding='utf-8')

# 绝对路径(Windows)
file4 = open(r'C:UsersAdministratorDesktopdata.txt', 'r', encoding='utf-8')

# 绝对路径(Linux/Mac)
file5 = open('/home/user/data.txt', 'r', encoding='utf-8')

6.2 使用os.path处理路径

# 示例28:使用os.path处理路径
import os

# 获取当前工作目录
current_dir = os.getcwd()
print('当前目录:', current_dir)

# 拼接路径
file_path = os.path.join('folder', 'subfolder', 'data.txt')
print('文件路径:', file_path)

# 检查文件是否存在
if os.path.exists(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
else:
    print('文件不存在')

# 获取文件所在目录
dir_path = os.path.dirname(file_path)
print('目录路径:', dir_path)

# 获取文件名
filename = os.path.basename(file_path)
print('文件名:', filename)

6.3 使用pathlib处理路径(Python 3.4+)

# 示例29:使用pathlib处理路径(推荐方式)
from pathlib import Path

# 创建Path对象
file_path = Path('folder') / 'subfolder' / 'data.txt'
print('文件路径:', file_path)

# 检查文件是否存在
if file_path.exists():
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()

# 获取父目录
parent_dir = file_path.parent
print('父目录:', parent_dir)

# 获取文件名
filename = file_path.name
print('文件名:', filename)

# 获取文件扩展名
extension = file_path.suffix
print('扩展名:', extension)

6.4 创建目录

# 示例30:创建目录后写入文件
import os
from pathlib import Path

# 方法1:使用os.makedirs
file_path = 'new_folder/sub_folder/data.txt'
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'w', encoding='utf-8') as file:
    file.write('内容')

# 方法2:使用pathlib
file_path = Path('new_folder/sub_folder/data.txt')
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, 'w', encoding='utf-8') as file:
    file.write('内容')

7. 文件编码问题

7.1 什么是编码

编码是将字符转换为字节的过程。常见的编码格式有:

  • UTF-8:最常用的编码,支持所有字符
  • GBK/GB2312:中文编码
  • ASCII:只支持英文字符

7.2 指定文件编码

# 示例31:指定文件编码
# UTF-8编码(推荐)
with open('utf8_file.txt', 'w', encoding='utf-8') as file:
    file.write('这是UTF-8编码的文件n')
    file.write('支持中文、英文、emoji 😊n')

# GBK编码(中文Windows系统常用)
with open('gbk_file.txt', 'w', encoding='gbk') as file:
    file.write('这是GBK编码的文件n')

# 读取时也要指定相同的编码
with open('utf8_file.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

7.3 编码错误处理

# 示例32:处理编码错误
# errors参数可以指定错误处理方式
# 'strict':默认,遇到错误抛出异常
# 'ignore':忽略错误
# 'replace':用替换字符替换错误字符

# 严格模式(默认)
try:
    with open('file.txt', 'r', encoding='utf-8') as file:
        content = file.read()
except UnicodeDecodeError as e:
    print('编码错误:', e)

# 忽略错误
with open('file.txt', 'r', encoding='utf-8', errors='ignore') as file:
    content = file.read()

# 替换错误字符
with open('file.txt', 'r', encoding='utf-8', errors='replace') as file:
    content = file.read()

7.4 检测文件编码

# 示例33:检测文件编码(需要安装chardet库)
# pip install chardet

import chardet

def detect_encoding(file_path):
    with open(file_path, 'rb') as file:
        raw_data = file.read()
        result = chardet.detect(raw_data)
        return result['encoding']

# 使用示例
encoding = detect_encoding('unknown_file.txt')
print(f'检测到的编码:{encoding}')

with open('unknown_file.txt', 'r', encoding=encoding) as file:
    content = file.read()

8. 异常处理

8.1 文件操作常见异常

# 示例34:文件操作常见异常
# FileNotFoundError:文件不存在
try:
    with open('not_exist.txt', 'r', encoding='utf-8') as file:
        content = file.read()
except FileNotFoundError:
    print('文件不存在!')

# PermissionError:权限不足
try:
    with open('protected_file.txt', 'w', encoding='utf-8') as file:
        file.write('内容')
except PermissionError:
    print('没有写入权限!')

# IsADirectoryError:路径是目录而不是文件
try:
    with open('some_directory', 'r', encoding='utf-8') as file:
        content = file.read()
except IsADirectoryError:
    print('这是一个目录,不是文件!')

8.2 完整的异常处理示例

# 示例35:完整的文件操作异常处理
def read_file_safely(file_path):
    """安全地读取文件"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
            return content
    except FileNotFoundError:
        print(f'错误:文件 {file_path} 不存在')
        return None
    except PermissionError:
        print(f'错误:没有权限读取文件 {file_path}')
        return None
    except UnicodeDecodeError:
        print(f'错误:文件 {file_path} 编码错误')
        return None
    except Exception as e:
        print(f'发生未知错误:{e}')
        return None

# 使用示例
content = read_file_safely('example.txt')
if content:
    print(content)

8.3 写入文件的异常处理

# 示例36:写入文件的异常处理
def write_file_safely(file_path, content):
    """安全地写入文件"""
    try:
        # 确保目录存在
        import os
        os.makedirs(os.path.dirname(file_path), exist_ok=True)

        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(content)
        print(f'文件 {file_path} 写入成功')
        return True
    except PermissionError:
        print(f'错误:没有权限写入文件 {file_path}')
        return False
    except OSError as e:
        print(f'错误:无法写入文件 {file_path},原因:{e}')
        return False
    except Exception as e:
        print(f'发生未知错误:{e}')
        return False

# 使用示例
write_file_safely('output.txt', '这是要写入的内容')

9. 实际应用示例

9.1 读取配置文件

# 示例37:读取配置文件
def read_config(config_file='config.txt'):
    """读取配置文件,返回字典"""
    config = {}
    try:
        with open(config_file, 'r', encoding='utf-8') as file:
            for line in file:
                line = line.strip()  # 去除首尾空白
                if line and not line.startswith('#'):  # 忽略空行和注释
                    if '=' in line:
                        key, value = line.split('=', 1)
                        config[key.strip()] = value.strip()
        return config
    except FileNotFoundError:
        print(f'配置文件 {config_file} 不存在')
        return {}

# 配置文件示例(config.txt):
# username=admin
# password=123456
# host=localhost
# port=8080

config = read_config('config.txt')
print(config)

9.2 日志记录

# 示例38:简单的日志记录功能
import datetime

def write_log(message, log_file='app.log'):
    """写入日志"""
    timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    log_entry = f'[{timestamp}] {message}n'

    with open(log_file, 'a', encoding='utf-8') as file:
        file.write(log_entry)

# 使用示例
write_log('程序启动')
write_log('用户登录成功')
write_log('处理数据完成')

9.3 数据备份

# 示例39:文件备份功能
import shutil
from pathlib import Path

def backup_file(source_file, backup_dir='backup'):
    """备份文件"""
    source_path = Path(source_file)
    if not source_path.exists():
        print(f'源文件 {source_file} 不存在')
        return False

    # 创建备份目录
    backup_path = Path(backup_dir)
    backup_path.mkdir(exist_ok=True)

    # 生成备份文件名(添加时间戳)
    timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
    backup_file = backup_path / f'{source_path.stem}_{timestamp}{source_path.suffix}'

    # 复制文件
    shutil.copy2(source_path, backup_file)
    print(f'文件已备份到:{backup_file}')
    return True

# 使用示例
backup_file('important_data.txt')

9.4 CSV文件处理

# 示例40:简单的CSV文件读写
def write_csv(data, filename):
    """写入CSV文件"""
    with open(filename, 'w', encoding='utf-8') as file:
        for row in data:
            # 将列表转换为CSV格式(用逗号分隔)
            line = ','.join(str(item) for item in row)
            file.write(line + 'n')

def read_csv(filename):
    """读取CSV文件"""
    data = []
    with open(filename, 'r', encoding='utf-8') as file:
        for line in file:
            # 分割CSV行
            row = line.strip().split(',')
            data.append(row)
    return data

# 使用示例
# 写入数据
data = [
    ['姓名', '年龄', '城市'],
    ['张三', 25, '北京'],
    ['李四', 30, '上海'],
    ['王五', 28, '广州']
]
write_csv(data, 'users.csv')

# 读取数据
read_data = read_csv('users.csv')
for row in read_data:
    print(row)

9.5 文件内容统计

# 示例41:统计文件信息
def file_statistics(filename):
    """统计文件的行数、字符数、单词数"""
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            lines = file.readlines()

        line_count = len(lines)
        char_count = sum(len(line) for line in lines)
        word_count = sum(len(line.split()) for line in lines)

        stats = {
            '行数': line_count,
            '字符数': char_count,
            '单词数': word_count
        }
        return stats
    except FileNotFoundError:
        print(f'文件 {filename} 不存在')
        return None

# 使用示例
stats = file_statistics('example.txt')
if stats:
    for key, value in stats.items():
        print(f'{key}:{value}')

9.6 文件内容搜索

# 示例42:在文件中搜索关键词
def search_in_file(filename, keyword):
    """在文件中搜索关键词,返回匹配的行号"""
    matches = []
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            for line_num, line in enumerate(file, start=1):
                if keyword in line:
                    matches.append({
                        '行号': line_num,
                        '内容': line.strip()
                    })
        return matches
    except FileNotFoundError:
        print(f'文件 {filename} 不存在')
        return []

# 使用示例
results = search_in_file('example.txt', '关键词')
for match in results:
    print(f"第{match['行号']}行:{match['内容']}")

9.7 文件合并

# 示例43:合并多个文件
def merge_files(file_list, output_file):
    """合并多个文件到一个文件"""
    try:
        with open(output_file, 'w', encoding='utf-8') as outfile:
            for filename in file_list:
                try:
                    with open(filename, 'r', encoding='utf-8') as infile:
                        outfile.write(f'n=== {filename} ===n')
                        outfile.write(infile.read())
                        outfile.write('n')
                except FileNotFoundError:
                    print(f'警告:文件 {filename} 不存在,跳过')
        print(f'文件已合并到 {output_file}')
        return True
    except Exception as e:
        print(f'合并文件时出错:{e}')
        return False

# 使用示例
files = ['file1.txt', 'file2.txt', 'file3.txt']
merge_files(files, 'merged.txt')

10. 常见问题与注意事项

10.1 常见错误

错误1:忘记关闭文件

# 错误示例
file = open('example.txt', 'r', encoding='utf-8')
content = file.read()
# 忘记关闭文件!

# 正确做法:使用with语句
with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()

错误2:文件路径错误

# 错误示例:路径中的反斜杠需要转义或使用原始字符串
file = open('C:UsersAdministratorfile.txt', 'r')  # 错误!

# 正确做法1:使用原始字符串
file = open(r'C:UsersAdministratorfile.txt', 'r')

# 正确做法2:使用正斜杠
file = open('C:/Users/Administrator/file.txt', 'r')

# 正确做法3:使用os.path.join
import os
file = open(os.path.join('C:', 'Users', 'Administrator', 'file.txt'), 'r')

错误3:编码不匹配

# 错误示例:写入和读取时编码不一致
with open('file.txt', 'w', encoding='gbk') as file:
    file.write('中文内容')

with open('file.txt', 'r', encoding='utf-8') as file:  # 编码不匹配!
    content = file.read()  # 可能出错

# 正确做法:使用相同的编码
with open('file.txt', 'w', encoding='utf-8') as file:
    file.write('中文内容')

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

10.2 最佳实践

实践1:始终使用with语句

# 推荐:使用with语句
with open('file.txt', 'r', encoding='utf-8') as file:
    content = file.read()

# 不推荐:手动管理文件
file = open('file.txt', 'r', encoding='utf-8')
content = file.read()
file.close()

实践2:明确指定编码

# 推荐:明确指定编码
with open('file.txt', 'r', encoding='utf-8') as file:
    content = file.read()

# 不推荐:使用默认编码(可能因系统而异)
with open('file.txt', 'r') as file:
    content = file.read()

实践3:处理异常

# 推荐:处理可能的异常
try:
    with open('file.txt', 'r', encoding='utf-8') as file:
        content = file.read()
except FileNotFoundError:
    print('文件不存在')
except Exception as e:
    print(f'发生错误:{e}')

实践4:大文件使用迭代读取

# 推荐:大文件使用迭代读取
with open('large_file.txt', 'r', encoding='utf-8') as file:
    for line in file:
        process(line)  # 逐行处理

# 不推荐:一次性读取大文件
with open('large_file.txt', 'r', encoding='utf-8') as file:
    content = file.read()  # 可能内存不足
    process(content)

10.3 性能优化建议

# 示例44:性能优化技巧

# 1. 使用缓冲(默认已启用)
with open('file.txt', 'r', encoding='utf-8', buffering=8192) as file:
    content = file.read()

# 2. 批量写入(减少I/O操作)
lines = ['行1n', '行2n', '行3n']
with open('file.txt', 'w', encoding='utf-8') as file:
    file.writelines(lines)  # 比多次write()更高效

# 3. 使用二进制模式处理大文件
with open('large_file.bin', 'rb') as file:
    chunk = file.read(1024 * 1024)  # 每次读取1MB

10.4 文件操作检查清单

在进行文件操作时,请检查以下事项:

  • [ ] 文件路径是否正确?
  • [ ] 文件是否存在(读取时)?
  • [ ] 是否有足够的权限?
  • [ ] 是否指定了正确的编码?
  • [ ] 是否使用了with语句?
  • [ ] 是否处理了可能的异常?
  • [ ] 大文件是否使用了迭代读取?
  • [ ] 写入后是否需要刷新缓冲区?

总结

Python的文件操作是编程中的基础技能,掌握以下几点非常重要:

  1. 基本操作:打开、读取、写入、关闭文件
  2. 打开模式:理解不同模式的区别和用途
  3. with语句:自动管理文件,避免资源泄漏
  4. 编码处理:正确处理文件编码,避免乱码
  5. 异常处理:妥善处理文件操作中的各种异常
  6. 路径处理:正确使用相对路径和绝对路径
  7. 最佳实践:遵循Python的文件操作最佳实践

通过大量的练习和实践,你将能够熟练地进行各种文件操作,为更复杂的程序开发打下坚实的基础。


练习题

练习1:文件复制器

编写一个函数,将一个文件的内容复制到另一个文件。

练习2:行号添加器

编写一个程序,读取文件并在每行前添加行号,然后保存到新文件。

练习3:文件比较器

编写一个函数,比较两个文件的内容是否相同。

练习4:单词计数器

编写一个程序,统计文件中每个单词出现的次数。

练习5:配置文件解析器

编写一个程序,解析类似INI格式的配置文件。


祝你学习愉快!

发表评论