如何在Python中查找递归空目录?
与GNU如何在Python中查找递归空目录?,python,directory-structure,subdirectory,Python,Directory Structure,Subdirectory,与GNUfind类似,我希望找到空目录,包括那些具有空子目录的目录(以及包含emtpy子目录等的子目录),但不删除它们。是否有任何现有的解决方案,或者我必须手动使用os.walk(可能使用top-down=False,并跟踪到目前为止找到的空子目录)?好的,这是我使用os.walk的手动解决方案。函数是空的当然可以修改,例如排除隐藏文件,或者在我的示例中desktop.ini: import os def empty_dirs(root_dir='.', recursive=True):
find
类似,我希望找到空目录,包括那些具有空子目录的目录(以及包含emtpy子目录等的子目录),但不删除它们。是否有任何现有的解决方案,或者我必须手动使用os.walk
(可能使用top-down=False
,并跟踪到目前为止找到的空子目录)?好的,这是我使用os.walk
的手动解决方案。函数是空的
当然可以修改,例如排除隐藏文件,或者在我的示例中desktop.ini
:
import os
def empty_dirs(root_dir='.', recursive=True):
empty_dirs = []
for root, dirs, files in os.walk(root_dir, topdown=False):
#print root, dirs, files
if recursive:
all_subs_empty = True # until proven otherwise
for sub in dirs:
full_sub = os.path.join(root, sub)
if full_sub not in empty_dirs:
#print full_sub, "not empty"
all_subs_empty = False
break
else:
all_subs_empty = (len(dirs) == 0)
if all_subs_empty and is_empty(files):
empty_dirs.append(root)
yield root
def is_empty(files):
return (len(files) == 0 or files == ['desktop.ini'])
def find_empty_dirs(root_dir='.', recursive=True):
return list(empty_dirs(root_dir, recursive))
print find_empty_dirs(recursive=False)
下面是一个使用生成器和操作系统的简单解决方案。walk:
import os
def find_empty_dirs(root_dir='.'):
for dirpath, dirs, files in os.walk(root_dir):
if not dirs and not files:
yield dirpath
print list(find_empty_dirs())
我不明白为什么top-down=False
是必要的,我认为它不会改变任何事情
<>这确实考虑了目录,这些目录只包含空目录本身非空,但是代码< >查找也如此。类型d-空
不过,通过更多的测试,我看到了find-键入d-empty-delete
首先删除空的子目录,然后删除更高的目录(如果这使它们为空)。但是使用os.walk进行这项操作是行不通的,因为它会在降序之前读取子目录列表,即使使用top-down=False
删除空子目录树的递归解决方案可以是:
import os
def recursive_delete_if_empty(path):
"""Recursively delete empty directories; return True
if everything was deleted."""
if not os.path.isdir(path):
# If you also want to delete some files like desktop.ini, check
# for that here, and return True if you delete them.
return False
# Note that the list comprehension here is necessary, a
# generator expression would shortcut and we don't want that!
if all([recursive_delete_if_empty(os.path.join(path, filename))
for filename in os.listdir(path)]):
# Either there was nothing here or it was all deleted
os.rmdir(path)
return True
else:
return False
如果我确定要在Unix上运行,我会尝试使用
os.walk
,或Popen
+find
/Linux@SergeBallesta前者也是我目前为止最好的猜测。我想知道它是否没有库函数。。。或者可能是查找
模块。这可能会简化很多事情。@SergeBallesta I,希望这是足够的Pythonic…@Close vote我不是在寻找一个库推荐,仅仅是寻找一种Pythonic的方式来实现find
的功能(以可移植的方式)。当然,“库XY以Z的形式实现这一点”将是一个有效的答案。我添加了一个手动递归解决方案。好奇-啊,我在问题中看到了我的错误,find-d类型-empty
只能以递归方式工作,就像我在使用-delete
时所说的那样。恐怕我必须解决我的问题,虽然您的输入很受欢迎,但生成器听起来确实更好。我修改为包含生成器,但到目前为止,我必须存储到目前为止找到的所有空子目录,这就是为什么我需要top down=False
。但也许有更简单的方法