【问题标题】:How to loop over multiple directories in python如何在python中循环多个目录
【发布时间】:2019-11-10 02:13:52
【问题描述】:

如何让这段代码循环遍历 CHEST_ICONS 的所有子目录 包括目录,最后有一些我想转换成 jpg 的 .dcm 图标?
CHEST_ICONS 包括 CPTAC-SAR 目录。 CPTAC-SAR 包括 C3L-03196 和 C3L-01038,每个都包括 1 个目录,其中包括最后一个带有 .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

提前致谢。任何帮助将不胜感激。

【问题讨论】:

  • 您是尝试在 folder_path 中的每个路径上运行 listdir,还是递归地在 CHEST_ICOSN 中的所有文件夹上运行?
  • @ollien 我想从每个子目录进入 lasts 目录,并将 .dcm 文件从它们转换为 jpg。

标签: python directory operating-system


【解决方案1】:

正确的方法是:

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

【讨论】:

    【解决方案2】:

    您的folder_path 似乎指向比 CHEST_ICONS 更远的文件或目录。如果您以 CHEST_ICONS 结尾,那么您可以递归地使用os.listdir() 来访问在该点之后找到的任何目录。取决于目录中有多少,尽管您的运行时可能很长...

    【讨论】:

    • 是的,我知道我只是想指出我想访问此目录以及其他目录。对不起,如果我被误解了。
    • 啊,在这种情况下,lenik 的答案似乎是最好的方法。我之前没见过os.walk() 方法。很有用...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多