如何在python中循环多个目录

2024-06-02 05:32:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎样才能使这个代码在所有图标的子目录中循环 包括目录,最后还有一些.dcm图标,我想转换成jpg?
胸部图标包括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

提前谢谢。任何帮助都将受到感激


Tags: 文件path代码目录folder图标jpgimages
2条回答

正确的方法是:

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

看起来您folder_path指向的是比图标更靠下的文件或目录。如果以图标结尾,那么可以递归地使用os.listdir()来点击在该点之后找到的任何目录。虽然你的运行时间可能很长,但这取决于目录中有多少内容

相关问题 更多 >