You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何更优雅地在多个函数前执行重复的文件检查操作

优雅复用文件检查-读取/创建逻辑的方案

你可以把重复的文件判断、读写逻辑封装成通用函数,直接返回需要的列表,这比装饰器更直接,也能完美解决复用问题。

核心思路

把“文件存在则读取为列表,不存在则执行处理函数生成数据并写入文件”的逻辑抽离成独立函数,每次使用只需传入文件路径和对应的处理函数(负责生成要写入的数据列表)。

实现代码

import os

def get_or_create_file_list(filepath, generate_data_func):
    # 检查文件是否存在
    if not os.path.exists(filepath):
        # 执行处理函数生成要写入的数据列表
        data_list = generate_data_func()
        # 写入文件
        with open(filepath, 'w') as f:
            for item in data_list:
                f.write(f"{item}\n")
        # 返回刚生成的列表
        return data_list
    else:
        # 读取现有文件并转为列表(去除每行末尾的换行符)
        with open(filepath, 'r') as f:
            return [line.rstrip() for line in f]

使用示例

1. 无参数的处理函数

假设你的foo()函数负责生成要写入的数据:

def foo():
    # 模拟业务逻辑:生成需要写入文件的内容
    return ["user_alice", "user_bob", "user_charlie"]

# 调用通用函数
filename = "user_list.txt"
filepath = os.path.join(os.getcwd(), filename)
user_list = get_or_create_file_list(filepath, foo)

2. 带参数的处理函数

如果处理函数需要传入参数,可以用lambda包装后传递:

def bar(prefix, count):
    # 根据参数生成数据
    return [f"{prefix}_{i}" for i in range(count)]

# 用lambda传递参数给处理函数
another_file = "product_codes.txt"
product_list = get_or_create_file_list(
    os.path.join(os.getcwd(), another_file),
    lambda: bar("PROD", 10)
)

可选优化:增加异常处理

如果需要让函数更健壮,可以添加异常捕获逻辑:

def get_or_create_file_list(filepath, generate_data_func):
    try:
        if not os.path.exists(filepath):
            data_list = generate_data_func()
            with open(filepath, 'w') as f:
                for item in data_list:
                    f.write(f"{item}\n")
            return data_list
        else:
            with open(filepath, 'r') as f:
                return [line.rstrip() for line in f]
    except IOError as e:
        print(f"文件操作失败: {e}")
        raise  # 抛出异常让调用方处理,或者根据需求返回空列表等

这个方案的优势在于:

  • 完全消除重复代码,所有文件的检查、读写逻辑都集中在一个函数里
  • 灵活适配不同的处理函数(有无参数都能处理)
  • 直接返回所需的列表,完美解决你用装饰器遇到的返回值问题

内容的提问来源于stack exchange,提问作者ReLisK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 16:00:20