python-2.7 - 目录和文件的 Python 递归到 5 个级别
问题描述
我正在寻找一个更优雅的解决方案来解决我在尝试递归到多个级别以列出目录和文件时遇到的问题。
os.walk(folder)
做子和子子级别,但我至少需要深入5。
我想出了以下遍历多个目录的方法,但是,有没有更好或更优雅的方法我错过了?
rootPath = '/path/to/my/folder/test'
print '###### using os.walk ######'
for root, dirs, files in os.walk(rootPath):
print 'directory - ' + " ".join(dirs)
for d in dirs:
for f in files:
if not f.startswith('.'):
print 'directory - ' + d + ' file - ' + f
print '\n\n\n###### using isdir ######'
for f in os.listdir(rootPath):
print '-' + f
if os.path.isdir(os.path.join(rootPath,f)):
for fo in os.listdir(os.path.join(rootPath,f)):
print '--' + fo
if os.path.isdir(os.path.join(rootPath,f,fo)):
for fol in os.listdir(os.path.join(rootPath,f,fo)):
print '---' + fol
if os.path.isdir(os.path.join(rootPath,f,fo,fol)):
for fold in os.listdir(os.path.join(rootPath,f,fo,fol)):
print '----' + fold
if os.path.isdir(os.path.join(rootPath,f,fo,fol,fold)):
for folde in os.listdir(os.path.join(rootPath,f,fo,fol,fold)):
print '-----' + folde
if os.path.isdir(os.path.join(rootPath,f,fo,fol,fold,folde)):
for folder in os.listdir(os.path.join(rootPath,f,fo,fol,fold,folde)):
print '------' + folder
输出:
###### using os.walk ######
directory - first
directory - second
directory - third
directory - fourth
directory - fourth file - in_third.txt
directory - fifth
directory - fifth file - in_fourth.txt
directory -
###### using isdir ######
-.DS_Store
-first
---.DS_Store
---second
-----.DS_Store
-----third
------.DS_Store
------fourth
-------.DS_Store
-------in_fourth.txt
-------fifth
---------.DS_Store
---------in_fifth.txt
------in_third.txt
似乎 os.walk 没有进入“第五”文件夹以查看 in_fifth.txt,但是 isidr() 解决方案可以。
谢谢
解决方案
所以部分原因是我对 os.walk 工作原理的误解,我相信你需要用for d in dirs
. 但是,它似乎已经做到了for f in files
我通过让文件做它的事情来解决这个问题,然后用我最初提供的 rootPath 替换 root,因为我只想要整个路径字符串之后的目录名称。
rootPath = '/path/to/my/folder/test'
for root, dirs, files in os.walk(rootPath):
for f in files:
if not f.startswith('.'):
print 'file - ' + os.path.join(os.path.join(root.replace(rootPath,''), f))
输出:
file - /test2/first/foobar/files1.txt
file - /test2/first/foo.txt
file - /extra/test/bar.bin
推荐阅读
- php - 如何在私有子网 VPC 中将 PHP 连接到 MySQL
- android - android:物理键盘语言切换和鼠标点击在 EditText 中不起作用
- linux - __attribute__ ((weak)) 不适用于全局变量
- testing - spring 尝试在 Mocked 实例中注入 @Autowired 依赖项
- database - MongoDB couldn't start because have error
- r - 将 XTS 月份最后一个工作日索引转换为月份最后一天
- intellij-idea - Intelliji“问题”工具栏不显示问题
- ruby - 如何在 Ruby 中使用连字符格式化电话字符串?
- wordpress - 如何使用 Woocommerce REST API 从 Wordpress 为我的产品生成 API 端点?
- single-page-application - Web 服务器在托管单页应用程序中扮演什么角色