如何重构子文件夹内不同操作的文件

huangapple go评论69阅读模式
英文:

How to refactoring different actions on files inside subfolders

问题

我正在尝试将文件组织脚本功能化并清理。每个脚本都类似于这样:

for dir_level in dirs:
    dates = glob.glob(dir_level)
    for date in dates:
        files = glob.glob(date)
        for file in files:
            # 做一些操作

有什么干净的方法可以拥有相同的目录遍历逻辑(具有可变深度级别),但可以对该文件夹级别执行任意操作?

英文:

I am trying to functionalize and clean up file organization scripts. Each one is something like this:

for dir_level in dirs: 
    dates = glob.glob(dir_level)
    for date in dates: 
        files = glob.glob(date)
        for file in files: 
            # do_stuff

What is a clean way to have the same directory crawl logic (with variable number of depth levels) but arbitrary actions to be done on that folder level?

答案1

得分: 1

写函数来表示“执行操作”部分:

def example_action(filename):
    print(filename, '是一个有价值的有趣文件。')

然后使用一个单一函数来表示遍历,并将另一个函数作为高阶函数传递:

def on_each_file(dirs, action):
    for dir_level in dirs: 
        dates = glob.glob(dir_level)
        for date in dates: 
            files = glob.glob(date)
            for file in files: 
                action(file)

on_each_file(my_dirs, example_action)
英文:

Write functions to represent the "do stuff" part:

def example_action(filename):
    print(filename, 'is an interesting file that is worthy of consideration.')

Then use a single function to represent the traversal, and pass one of the other functions as a higher-order function:

def on_each_file(dirs, action):
    for dir_level in dirs: 
        dates = glob.glob(dir_level)
        for date in dates: 
            files = glob.glob(date)
            for file in files: 
                action(file)

on_each_file(my_dirs, example_action)

huangapple
  • 本文由 发表于 2023年2月24日 00:20:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定