1 文件对象

文件对象是Python中用来访问文件的接口,可以通过内置的open()函数创建。

# 打开文件的基本语法
file_object = open(filename, mode='r', buffering=-1)

# 示例:打开一个文本文件
f = open('example.txt', 'r')  # 'r'表示只读模式
print(f.read())  # 读取文件内容
f.close()  # 关闭文件

文件打开模式

  • 'r':读取(默认)1
  • 'w':写入(会覆盖已有文件)
  • 'a':追加
  • 'b':二进制模式
  • '+':读写模式

2 文件方法

读取方法

# read()方法读取整个文件
f = open('example.txt', 'r')
content = f.read()  # 读取全部内容
print(content)
f.close()

# readline()方法逐行读取
f = open('example.txt', 'r')
line = f.readline()  # 读取第一行
while line:
    print(line, end='')  # end=''避免打印多余的换行
    line = f.readline()
f.close()

# readlines()方法读取所有行到列表
f = open('example.txt', 'r')
lines = f.readlines()  # 返回包含所有行的列表
for line in lines:
    print(line, end='')
f.close()

写入方法

# write()方法写入字符串
f = open('output.txt', 'w')
f.write('Hello, World!\n')  # 写入一行
f.write('This is a test.\n')
f.close()

# writelines()方法写入字符串序列
lines = ['First line\n', 'Second line\n', 'Third line\n']
f = open('output.txt', 'w')
f.writelines(lines)  # 写入多行
f.close()

3 文件迭代

Python的文件对象是可迭代的,可以直接在for循环中使用:

# 使用for循环逐行读取文件(推荐方式)
with open('example.txt', 'r') as f:
    for line in f:
        print(line, end='')

4 上下文管理器(with语句)

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

# 使用with语句自动关闭文件
with open('example.txt', 'r') as f:
    data = f.read()
    print(data)
# 文件在这里已经自动关闭,无需调用f.close()

5 文件定位

# tell()方法获取当前位置
with open('example.txt', 'r') as f:
    print(f.tell())  # 当前位置(字节偏移量)
    f.read(10)  # 读取10个字符
    print(f.tell())  # 新位置

# seek()方法移动文件指针
with open('example.txt', 'rb') as f:  # 二进制模式更精确
    f.seek(5)  # 移动到第5个字节
    print(f.read(1))  # 读取第6个字节
    f.seek(0, 2)  # 移动到文件末尾
    print(f.tell())  # 文件总大小

6 标准文件

Python提供了三个标准文件对象:

  • sys.stdin:标准输入
  • sys.stdout:标准输出
  • sys.stderr:标准错误
import sys

# 重定向标准输出到文件
with open('output.txt', 'w') as f:
    sys.stdout = f  # 重定向标准输出
    print('This will be written to the file')
    sys.stdout = sys.__stdout__  # 恢复标准输出

print('This will be printed to console')

7 文件系统操作

osos.path模块提供了文件系统操作功能:

import os
import os.path

# 检查文件/目录是否存在
print(os.path.exists('example.txt'))  # True/False

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

# 检查是否是文件/目录
print(os.path.isfile('example.txt'))
print(os.path.isdir('example.txt'))

# 获取文件修改时间
print(os.path.getmtime('example.txt'))  # 返回时间戳

# 列出目录内容
print(os.listdir('.'))  # 当前目录下的文件和目录

# 创建/删除目录
os.mkdir('new_dir')  # 创建目录
os.rmdir('new_dir')  # 删除空目录

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

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

8 临时文件

tempfile模块可以创建临时文件和目录:

import tempfile

# 创建临时文件
temp_file = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
temp_file.write('Temporary data')
temp_file.close()

print(f"临时文件路径: {temp_file.name}")

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

# 删除临时文件
os.unlink(temp_file.name)

9 高级文件处理

1 文件压缩

import gzip
import bz2

# 使用gzip压缩文件
with open('example.txt', 'rb') as f_in:
    with gzip.open('example.txt.gz', 'wb') as f_out:
        f_out.write(f_in.read())

# 读取gzip文件
with gzip.open('example.txt.gz', 'rb') as f:
    print(f.read().decode('utf-8'))

# 使用bz2压缩文件
with open('example.txt', 'rb') as f_in:
    with bz2.open('example.txt.bz2', 'wb') as f_out:
        f_out.write(f_in.read())

2 CSV文件处理

import csv

# 写入CSV文件
with open('data.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['Alice', '25', 'New York'])
    writer.writerow(['Bob', '30', 'Chicago'])

# 读取CSV文件
with open('data.csv', 'r', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(', '.join(row))

3 JSON文件处理

import json

data = {
    'name': 'Alice',
    'age': 25,
    'city': 'New York',
    'hobbies': ['reading', 'hiking']
}

# 写入JSON文件
with open('data.json', 'w') as f:
    json.dump(data, f, indent=4)

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

 10 案例演示

案例1:写入和读取文本文件

# 写入文件
with open('example.txt', 'w', encoding='utf-8') as f:
    f.write('这是第一行文本\n')
    f.write('这是第二行文本\n')
    
# 读取文件
with open('example.txt', 'r', encoding='utf-8') as f:
    content = f.read()
    print(content)

应用场景

  • 保存程序配置或日志信息
  • 存储简单的文本数据
  • 读写配置文件

方法详解

  • open()函数:打开文件,参数1是文件名,参数2是模式('w'写/'r'读),参数3是编码
  • with语句:自动管理文件资源,确保文件正确关闭
  • write()方法:写入字符串到文件
  • read()方法:读取整个文件内容

案例2:逐行读取文件

with open('example.txt', 'r', encoding='utf-8') as f:
    for line in f:
        print(line.strip())  # strip()去除每行末尾的换行符

应用场景

  • 处理日志文件
  • 分析大型文本文件(避免一次性加载到内存)
  • 读取CSV或TSV格式数据

案例3:图片文件复制

with open('source.jpg', 'rb') as src:
    with open('copy.jpg', 'wb') as dst:
        dst.write(src.read())

应用场景

  • 图片、音频、视频等非文本文件处理
  • 文件加密/解密
  • 网络传输文件

方法详解

  • 'rb'/'wb'模式:以二进制模式读写
  • 二进制模式下不能指定编码
  • 适合处理任何类型的文件

案例4:JSON数据读写

import json

# 写入JSON
data = {'name': '张三', 'age': 25, 'skills': ['Python', 'Java']}
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

# 读取JSON
with open('data.json', 'r', encoding='utf-8') as f:
    loaded_data = json.load(f)
    print(loaded_data)

应用场景

  • 保存程序配置
  • Web API数据交换
  • 结构化数据存储

方法详解

  • json.dump():将Python对象序列化为JSON并写入文件
  • json.load():从文件读取JSON并反序列化为Python对象
  • ensure_ascii=False:允许非ASCII字符正常显示
  • indent=4:美化输出,增加可读性

案例5:CSV文件读写

import csv

# 写入CSV
data = [['姓名', '年龄', '城市'],
        ['张三', 25, '北京'],
        ['李四', 30, '上海']]

with open('people.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(data)

# 读取CSV
with open('people.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

应用场景

  • 数据分析和处理
  • 与Excel等表格软件交互
  • 数据库数据导出/导入

方法详解

  • csv.writer():创建CSV写入对象
  • writer.writerows():写入多行数据
  • csv.reader():创建CSV读取对象
  • newline='':防止在Windows上出现空行

案例6:文件路径操作

import os
from os import path

# 检查文件是否存在
print(path.exists('example.txt'))

# 获取文件大小
print(path.getsize('example.txt'))

# 获取文件修改时间
print(path.getmtime('example.txt'))

# 遍历目录
for item in os.listdir('.'):
    print(item)

应用场景

  • 文件管理系统
  • 批量处理文件
  • 文件监控和同步

方法详解

  • os.path模块:处理文件路径相关操作
  • os.listdir():列出目录内容
  • os.path.exists():检查文件/目录是否存在
  • os.path.getsize():获取文件大小(字节)

案例7:临时文件操作

import tempfile

# 创建临时文件
with tempfile.NamedTemporaryFile(delete=False) as tmp:
    tmp.write(b'临时数据')
    tmp_path = tmp.name

# 读取临时文件
with open(tmp_path, 'r') as f:
    print(f.read())

# 删除临时文件
os.unlink(tmp_path)

应用场景

  • 处理需要临时存储的数据
  • 大型数据处理中间结果
  • 安全敏感数据临时存储

方法详解

  • tempfile.NamedTemporaryFile():创建有名称的临时文件
  • delete=False:防止文件自动删除
  • os.unlink():删除文件

案例8:ZIP文件处理

import zipfile

# 创建ZIP文件
with zipfile.ZipFile('archive.zip', 'w') as zipf:
    zipf.write('example.txt')
    zipf.write('data.json')

# 读取ZIP文件
with zipfile.ZipFile('archive.zip', 'r') as zipf:
    zipf.extractall('extracted_files')
    print(zipf.namelist())

应用场景

  • 批量文件打包和分发
  • 数据备份
  • 压缩大型文件节省空间

方法详解

  • zipfile.ZipFile():创建或打开ZIP文件
  • write():添加文件到ZIP
  • extractall():解压所有文件
  • namelist():获取ZIP内文件列表

11. 文件操作进阶案例

案例1:日志文件分析器

def analyze_log(log_file):
    error_count = 0
    warning_count = 0
    with open(log_file) as f:
        for line in f:
            if 'ERROR' in line:
                error_count += 1
            elif 'WARNING' in line:
                warning_count += 1
    
    print(f"错误总数: {error_count}")
    print(f"警告总数: {warning_count}")
    return {'errors': error_count, 'warnings': warning_count}

# 使用示例
results = analyze_log('system.log')

        这个工具会逐行读取日志文件,检查每行是否包含 "ERROR" 或 "WARNING" 关键字,并分别统计它们的出现次数。最后打印统计结果并返回包含统计数据的字典。

代码结构解析

代码分为两个主要部分:

  1. analyze_log 函数:负责日志分析的核心功能

    • 初始化错误和警告计数器
    • 逐行读取日志文件
    • 检查每行是否包含 "ERROR" 或 "WARNING" 关键字
    • 更新相应的计数器
    • 打印统计结果并返回包含统计数据的字典
  2. 使用示例:演示如何使用 analyze_log 函数分析日志文件

案例2:CSV数据处理

import csv

def process_csv(input_file, output_file):
    with open(input_file) as fin, open(output_file, 'w') as fout:
        reader = csv.DictReader(fin)
        writer = csv.DictWriter(fout, fieldnames=reader.fieldnames)
        writer.writeheader()
        
        for row in reader:
            # 数据处理示例:将金额字段增加10%
            if 'amount' in row:
                row['amount'] = float(row['amount']) * 1.1
            writer.writerow(row)

# 使用示例
process_csv('sales.csv', 'sales_updated.csv')

案例3:目录遍历工具

import os

def find_files(directory, extension):
    """查找指定目录下特定扩展名的文件"""
    matches = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(extension):
                matches.append(os.path.join(root, file))
    return matches

# 使用示例
python_files = find_files('/projects', '.py')
print(f"找到 {len(python_files)} 个Python文件")

案例4:文件备份脚本

import shutil
import time

def backup_file(filename):
    """创建带时间戳的文件备份"""
    timestamp = time.strftime("%Y%m%d-%H%M%S")
    backup_name = f"{filename}.bak.{timestamp}"
    shutil.copy2(filename, backup_name)
    return backup_name

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

案例5:二进制文件处理

def encrypt_file(input_file, output_file, key=128):
    """简单的文件加密"""
    with open(input_file, 'rb') as fin, open(output_file, 'wb') as fout:
        while True:
            chunk = fin.read(1024)
            if not chunk:
                break
            # 简单的XOR加密
            encrypted = bytes([b ^ key for b in chunk])
            fout.write(encrypted)

# 使用示例
encrypt_file('secret.txt', 'secret.enc')

        这个工具通过逐块读取文件内容,并对每个字节执行 XOR 运算来实现加密。加密后的内容被写入到输出文件中。解密时,只需使用相同的密钥对加密文件再次执行 XOR 运算即可。

代码结构解析

代码分为两个主要部分:

  1. encrypt_file 函数:负责文件加密的核心功能

    • 以二进制模式打开输入和输出文件
    • 分块读取输入文件内容
    • 对每块内容的每个字节执行 XOR 运算
    • 将加密后的内容写入输出文件
  2. 使用示例:演示如何使用 encrypt_file 函数加密文件

关键代码详解

文件处理与分块读取

with open(input_file, 'rb') as fin, open(output_file, 'wb') as fout:
    while True:
        chunk = fin.read(1024)
        if not chunk:
            break
        # 处理数据块
  • 使用with语句同时打开输入和输出文件,确保文件资源正确关闭
  • 以二进制模式 ('rb''wb') 操作文件,确保正确处理所有类型的文件
  • 每次读取 1024 字节的数据块,避免一次性加载整个文件到内存中

XOR 加密实现

encrypted = bytes([b ^ key for b in chunk])

  • 使用列表推导式遍历数据块中的每个字节
  • 对每个字节执行 XOR 运算(^操作符)
  • 将结果转换为字节对象

XOR 加密原理

XOR 运算具有以下特性:

  • 对同一个值连续两次应用相同的密钥进行 XOR 运算,结果不变:(A ^ K) ^ K = A
  • 这使得 XOR 运算既可以用于加密,也可以用于解密

使用示例

encrypt_file('secret.txt', 'secret.enc')
  • 调用encrypt_file函数将secret.txt加密为secret.enc
  • 使用默认密钥值 128

代码优缺点分析

优点

  • 实现简单,代码量少
  • 不依赖任何外部库,仅使用 Python 标准库
  • 内存效率高,适合处理大文件
  • 加密和解密使用相同的算法和密钥,简化了实现

缺点

  • 安全性极低
    • 使用固定密钥,所有字节都使用相同的值进行 XOR
    • 容易受到频率分析攻击
    • 不提供身份验证和完整性保护
  • 没有错误处理,文件不存在或无法访问时会抛出异常
  • 没有密钥管理机制,密钥以明文形式硬编码或传递
  • 没有文件头或元数据,难以识别文件是否已加密

案例6:大文件分块处理

def process_large_file(filename, chunk_size=1024*1024):
    """分块处理大文件"""
    with open(filename, 'rb') as f:
        while True:
            chunk = f.read(chunk_size)
            if not chunk:
                break
            # 处理每个数据块
            yield process_chunk(chunk)

def process_chunk(chunk):
    """处理数据块的示例函数"""
    return len(chunk)

# 使用示例
total_size = 0
for size in process_large_file('huge_data.bin'):
    total_size += size
print(f"处理的总数据量: {total_size}字节")

         这段代码实现了一个分块处理大文件的工具,通过流式读取和处理文件数据,避免一次性加载整个文件到内存中,适用于处理 GB 级别的大文件。以下是详细讲解:

代码功能概述

  1. 核心目标:通过分块读取大文件,逐块处理数据,降低内存占用。
  2. 关键机制
    • 使用生成器(yield)实现流式处理,按需读取数据块。
    • 自定义chunk_size控制每次读取的数据量(默认 1MB)。
    • 提供可扩展的process_chunk函数,用于实现具体的数据处理逻辑(示例中仅统计块大小)。

代码结构解析

1. process_large_file 函数(主处理逻辑)

def process_large_file(filename, chunk_size=1024*1024):
    with open(filename, 'rb') as f:
        while True:
            chunk = f.read(chunk_size)  # 读取数据块
            if not chunk:  # 读取到文件末尾时退出循环
                break
            # 处理数据块并通过生成器返回结果
            yield process_chunk(chunk)
  • 参数
    • filename:目标文件名(需为二进制文件,以'rb'模式打开)。
    • chunk_size:每次读取的块大小(默认 1MB,即1024*1024字节)。
  • 流程
    1. 以二进制模式打开文件,确保处理所有类型的数据(如图像、视频、压缩文件等)。
    2. 循环读取chunk_size大小的数据块,直到文件末尾(chunk为空)。
    3. 对每个数据块调用process_chunk函数处理,并通过yield返回处理结果。
  • 关键点
    • 使用with语句确保文件正确关闭。
    • 生成器模式允许调用方逐块处理数据,避免内存溢出。

2. process_chunk 函数(自定义处理逻辑)

def process_chunk(chunk):
    """处理数据块的示例函数"""
    return len(chunk)  # 示例:返回块大小(字节数)
  • 这是一个可替换的函数,用于实现具体的数据处理逻辑,例如:
    • 数据清洗(过滤无效字节)。
    • 加密 / 解密(如前文中的 XOR 运算)。
    • 解析二进制协议(如解析图像文件的头部信息)。
    • 统计分析(如计算块内特定字节的出现次数)。

3. 使用示例(统计总数据量)

total_size = 0
for size in process_large_file('huge_data.bin'):
    total_size += size
print(f"处理的总数据量: {total_size}字节")
  • 遍历生成器process_large_file,累加每个数据块的处理结果(示例中为块大小)。
  • 最终输出文件总大小,与直接使用os.path.getsize的结果一致,但适用于文件动态增长的场景。

代码优缺点分析

优点

  1. 内存高效:每次仅加载chunk_size大小的数据到内存,支持处理远超物理内存的大文件。

  2. 可扩展性强:通过修改process_chunk函数,可灵活适配不同的处理需求(如转换格式、分析数据等)。

  3. 流式处理:生成器模式支持与其他流式处理工具(如迭代器、生成器表达式)无缝对接。

缺点

  1. 仅适用于顺序处理:无法随机访问文件中的特定块(如需随机访问,需记录块偏移量)。

  2. 二进制模式限制:当前代码仅处理二进制文件,若需处理文本文件,需指定编码(如'r'模式 +encoding参数)。

  3. 错误处理缺失:未处理文件不存在、权限不足等异常情况(需手动添加try-except)。

案例7:文件差异比较

import difflib

def compare_files(file1, file2):
    with open(file1) as f1, open(file2) as f2:
        diff = difflib.unified_diff(
            f1.readlines(),
            f2.readlines(),
            fromfile=file1,
            tofile=file2
        )
        return ''.join(diff)

# 使用示例
diff_result = compare_files('version1.py', 'version2.py')
print(diff_result)

案例8:自动文件编码检测

import chardet

def detect_encoding(filename):
    with open(filename, 'rb') as f:
        rawdata = f.read()
    return chardet.detect(rawdata)['encoding']

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

案例9:配置文件管理器

import configparser
import os

class ConfigManager:
    def __init__(self, config_file):
        self.config_file = config_file
        self.config = configparser.ConfigParser()
        if os.path.exists(config_file):
            self.config.read(config_file)
    
    def get_value(self, section, key, default=None):
        try:
            return self.config.get(section, key)
        except (configparser.NoSectionError, configparser.NoOptionError):
            return default
    
    def set_value(self, section, key, value):
        if not self.config.has_section(section):
            self.config.add_section(section)
        self.config.set(section, key, value)
    
    def save(self):
        with open(self.config_file, 'w') as f:
            self.config.write(f)

# 使用示例
config = ConfigManager('app.ini')
db_host = config.get_value('Database', 'host', 'localhost')
config.set_value('Database', 'port', '5432')
config.save()

        这个工具提供了一个面向对象的接口,用于操作 INI 格式的配置文件。它支持读取配置项、设置新配置项以及将更改保存回文件,同时提供了默认值机制以增强健壮性。

代码结构解析

代码分为两个主要部分:

  1. ConfigManager 类:负责配置文件的核心操作

    • __init__方法:初始化配置管理器,加载现有配置文件
    • get_value方法:获取配置项的值,支持默认值
    • set_value方法:设置配置项的值
    • save方法:将配置更改保存到文件
  2. 使用示例:演示如何使用 ConfigManager 类操作配置文件

关键方法详解

__init__方法

def __init__(self, config_file):
    self.config_file = config_file
    self.config = configparser.ConfigParser()
    if os.path.exists(config_file):
        self.config.read(config_file)
  • 初始化时接收配置文件路径
  • 创建configparser.ConfigParser对象用于处理 INI 文件
  • 如果配置文件存在,则读取其内容

get_value方法

def get_value(self, section, key, default=None):
    try:
        return self.config.get(section, key)
    except (configparser.NoSectionError, configparser.NoOptionError):
        return default
  • 尝试从指定的节 (section) 中获取键 (key) 对应的值
  • 如果节或键不存在,捕获异常并返回默认值
  • 提供了默认参数default=None,增强了方法的灵活性

set_value方法

def set_value(self, section, key, value):
    if not self.config.has_section(section):
        self.config.add_section(section)
    self.config.set(section, key, value)
  • 如果指定的节不存在,则创建该节
  • 设置指定节中键对应的值
  • 不会立即保存到文件,需要调用save()方法

save方法

def save(self):
    with open(self.config_file, 'w') as f:
        self.config.write(f)
  • 以写入模式打开配置文件
  • 将内存中的配置项写入文件
  • 使用with语句确保文件资源正确关闭

使用示例

config = ConfigManager('app.ini')
db_host = config.get_value('Database', 'host', 'localhost')
config.set_value('Database', 'port', '5432')
config.save()

  • 创建配置管理器实例,操作app.ini文件
  • Database节获取host配置项,默认值为localhost
  • 设置Database节的port配置项为5432
  • 将更改保存到文件

代码优缺点分析

优点

  • 实现简单,提供了清晰的 API 接口
  • 支持默认值机制,增强了代码的健壮性
  • 自动处理配置节的创建
  • 使用with语句确保文件操作的安全性

缺点

  • 没有处理文件权限或写入错误等异常情况
  • 不支持注释,保存文件时会丢失原有的注释
  • 不支持更复杂的配置格式,如嵌套结构
  • 每次保存都会覆盖原文件,可能导致权限变化

案例10:文件监控系统

import time
import hashlib

class FileMonitor:
    def __init__(self, file_path):
        self.file_path = file_path
        self.last_hash = self._get_file_hash()
    
    def _get_file_hash(self):
        with open(self.file_path, 'rb') as f:
            return hashlib.md5(f.read()).hexdigest()
    
    def check_for_changes(self):
        current_hash = self._get_file_hash()
        if current_hash != self.last_hash:
            self.last_hash = current_hash
            return True
        return False

# 使用示例
monitor = FileMonitor('important.log')
while True:
    if monitor.check_for_changes():
        print("文件已更改!")
    time.sleep(5)

        这个工具会持续监控指定文件的内容变化,一旦发现文件被修改,就会输出提示信息。它通过计算文件内容的 MD5 哈希值来判断文件是否发生变化。

代码结构解析

代码分为两个主要部分:

  1. FileMonitor 类:负责文件监控的核心功能

    • __init__方法:初始化监控器,记录文件的初始哈希值
    • _get_file_hash方法:计算文件内容的 MD5 哈希值
    • check_for_changes方法:检查文件是否发生变化
  2. 使用示例:演示如何使用 FileMonitor 类监控文件

关键方法详解

_get_file_hash方法

def _get_file_hash(self):
    with open(self.file_path, 'rb') as f:
        return hashlib.md5(f.read()).hexdigest()
  • 以二进制模式打开文件('rb'),确保正确处理所有类型的文件
  • 读取文件全部内容并计算 MD5 哈希值
  • 返回哈希值的十六进制表示形式

check_for_changes方法

def check_for_changes(self):
    current_hash = self._get_file_hash()
    if current_hash != self.last_hash:
        self.last_hash = current_hash
        return True
    return False
  • 计算当前文件的哈希值并与上次记录的哈希值比较
  • 如果不同,更新记录的哈希值并返回True(表示文件已更改)
  • 如果相同,返回False(表示文件未更改)

使用示例

monitor = FileMonitor('important.log')
while True:
    if monitor.check_for_changes():
        print("文件已更改!")
    time.sleep(5)
  • 创建一个监控器实例,监控important.log文件
  • 进入无限循环,每隔 5 秒检查一次文件是否变化
  • 发现变化时打印提示信息

代码优缺点分析

优点

  • 实现简单,易于理解和使用
  • 不依赖外部库,仅使用 Python 标准库
  • 适用于监控小文件的内容变化

缺点

  • 使用 MD5 哈希算法,安全性较低(但用于文件监控足够)
  • 每次检查都读取整个文件内容,对于大文件效率较低
  • 轮询方式检查,可能会漏掉两次检查之间的短暂修改
  • 没有处理文件不存在或无法访问的情况

最佳实践建议

  1. 1.始终使用with语句:确保文件正确关闭,即使在发生异常时
  2. 2.明确指定编码:特别是处理文本文件时,推荐使用'utf-8'
  3. 3.处理大文件要小心:使用逐行读取或分块读取避免内存问题
  4. 4.考虑跨平台兼容性:路径使用os.path.join(),换行符使用\n
  5. 5.注意文件权限:特别是在Linux/Unix系统上
Logo

更多推荐