如何在python中循环访问多个目录

问题描述 投票:-1回答:2

我如何使此代码遍历CHEST_ICONS的所有子目录包括目录,最后我想将某些.dcm图标转换为jpg吗?CHEST_ICONS包含CPTAC-SAR目录。 CPTAC-SAR包括C3L-03196和C3L-01038,它们每个都包含一个以上的目录,其中最后一个目录包含.dcm文件。

folder_path = "...DcmFIles\CHEST_ICONS\CPTAC-SAR\C3L-01038\10-31-2011-ABDOMEN-42992\2-92491"
images_path = os.listdir(folder_path)
for n, image in enumerate(images_path):
    do stuff

谢谢。任何帮助将不胜感激。

python directory operating-system
2个回答
0
投票

[看起来您folder_path指向的文件或目录比CHEST_ICONS更下层。如果您以CHEST_ICONS结尾,则可以递归使用os.listdir()击中此后找到的所有目录。尽管您的运行时间可能很长,但取决于目录中的内容数量...


0
投票

正确的方法是:

import os

for root, dirs, files in os.walk( folder_path ) :
    # root is the current folder (somewhere down the tree)
    # dirs contains all subfolder names in the current folder
    # files has all file names in the current folder
    for f in files :
        print( os.path.join( root, f ) )  # ought to `.join()` to get the full name
© www.soinside.com 2019 - 2024. All rights reserved.