python - 遍历目录,直到找到特定的文件夹名称
问题描述
我想通过一个目录向下走几层,直到找到一个以整数命名的文件夹,然后对文件夹内的东西进行某些操作。重要的是我仍然可以访问已处理文件夹的名称(整数),因为我使用它来命名操作的输出。我需要的文件夹名称中始终只有一个整数,没有其他字符。我尝试了一个有效的嵌套循环,但不幸的是我并不总是具有相同的深度(有时它会下降 2 个文件夹,有时会更多)
这是我到目前为止所得到的,它似乎适用于某些目录,但在其他目录上没有返回任何内容。
for root, dirs, files in os.walk("directory"):
for name in dirs:
try:
int(name.split("\\")[-1])
print(os.path.join(root, name))
except:
continue
可能会更好的是,循环在到达包含具有整数名称的文件夹的文件夹时立即停止,然后对这些整数子文件夹执行某些操作。
这样做最有效的方法是什么?
解决方案
你的代码很好。我只做了一些小的改动,让它更通用一点。让我知道什么不起作用,例如丢失的目录路径,我会改进我的答案。
import os
def process_folders(root_dn, f, op):
processed = []
for root, dirs, files in os.walk(root_dn):
for dn in dirs:
if f(dn):
path = os.path.join(root, dn)
rv = op(dn, path)
processed += [(dn, path, rv)]
return processed
# This is the function that tests if the directory name is one you're looking for
def dn_filter(s):
rv = True
try:
int(s)
except:
rv = False
return rv
# -or-
#return s in in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# This is the function that will process your directory. Return a value to indicate success
def dn_op(dn, path):
print('Processing:', dn, 'at', path)
return True
root_dn = '.'
processed = process_folders(root_dn, dn_filter, dn_op)
# Print all processed directories and their associated return values
for dn, path, success in processed:
print(dn, path, success)
推荐阅读
- git - Visual Studio 在 git push 上推送到错误的 URL:将分支推送到远程存储库时遇到错误:Git 失败并出现致命错误
- python - 从多个函数中拉出一个变量
- c - 分段错误 - 队列不会初始化
- nginx - Nginx 代理使用正则表达式将 mydomain.com/12345/ 传递到 12345.serverdomain.com
- sql - 在VB中使用IF语句和数据库材料
- python-3.x - 替换熊猫数据框中的特殊字符
- c# - 为什么我在使用 Entity Framework 和 ASP.NET Core 时收到此错误“System.InvalidOperationException”?
- c# - 如何使用 AddOutParameter 从存储过程中获取输出参数
- mysql - 外键索引
- javascript - 单击 x 可编辑和空 td