英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论