我正在编写一个程序,它需要探索给定路径自上而下的所有可能的子目录。我的问题是,我需要在调用递归之前和完成递归之后做一些事情,而os.walk()不允许这样做。更准确地说,我需要的目录子树中的递归是:
(注意:不是真正的Python代码,只是解释我需要做什么的类似Python的代码)
def recursion(path):
action1()
for subdir in path:
recursion(path+subdir)
action2()而我能用os.walk()做的事情很简单:
def recursion(path):
action1()
action2()
for subdir in path:
recursion(path+subdir)有什么解决方案吗?
发布于 2019-02-06 06:47:41
您可以改用os.scandir:
def recursion(path):
action1()
for entry in os.scandir(path):
if entry.is_dir():
recursion(os.path.join(path, entry.name))
action2()或者,如果您使用的是Python3.4或更早的版本,请使用速度较慢的os.listdir:
def recursion(path):
action1()
for name in os.listdir(path):
full_path = os.path.join(path, name)
if os.path.isdir(full_path):
recursion(full_path)
action2()发布于 2019-02-06 06:51:37
或者,您可以使用glob和split()
import glob
path='this/is/your/path'
pathElementList=path.split('/')
for x in range(len(pathElementList)):
directoryToDoActionIn='/'.join(pathElementList[0:x])
filesindir=glob.glob(directoryToDoActionIn+'/')
#do action with files herehttps://stackoverflow.com/questions/54544161
复制相似问题