【问题标题】:Display files from same folder name in different location在不同位置显示来自相同文件夹名称的文件
【发布时间】:2016-03-11 04:57:48
【问题描述】:

如何显示来自相同目录名称但位于子目录中的文件。考虑文件夹结构:

.
+ A
|   a.txt
|   b.txt
+ B
|   c.txt
|   d.txt
+ C
++   A
|      e.txt
++   B
+++      M
+++      B
|        g.txt
|   f.txt

现在如果我指定目录为B,它必须返回c.txtd.txtf.txtg.txt

我试过了:

for root, dirs, files in os.walk("D:/user/main"):
    for dirs in root:
        if dirs == root:
            print files

但它没有返回任何东西。我哪里错了?

【问题讨论】:

    标签: python file directory subdirectory


    【解决方案1】:

    尝试为每次迭代打印出根目录、目录和文件,这将有助于弄清楚会发生什么。

    "B" == root.split("\")[-1] 表示当前os.walk正在处理"D:/user/mian/xx/xx/B"

    len(files) 表示如果文件存在则打印出来,如果不存在则不打印。

    import os
    for root, dirs, files in os.walk("D:/user/main"):
        if "B" == root.split("\\")[-1] and len(files) > 0:
            print (files) 
    

    【讨论】:

    • ~ 非常感谢 :) 正是我想要的。
    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多