【问题标题】:Exclude specific folders and subfolders in os.walk排除 os.walk 中的特定文件夹和子文件夹
【发布时间】:2018-08-21 18:26:56
【问题描述】:

列出当前目录下所有带有 ext .txt 的文件。

L = [txt for f in os.walk('.') 
            for txt in glob(os.path.join(file[0], '*.txt'))]

我想避免来自一个特定目录及其子目录的文件。假设我不想深入研究folder3 及其可用子目录来获取.txt 文件。我在下面尝试过

d = list(filter(lambda x : x != 'folder3', next(os.walk('.'))[1]))

但进一步的步骤无法弄清楚。如何将两者包含在一起以协同工作?

编辑

我尝试将提供的链接引用为已回答的查询,但我无法在下面获得所需的输出,并且令人惊讶的是得到空列表作为 a 的输出

a=[]
for root, dirs, files in os.walk('.'):
  dirs[:] = list(filter(lambda x : x != 'folder3', dirs)) 
  for txt in glob(os.path.join(file[0], '*.txt')): 
      a.append(txt)

【问题讨论】:

  • 它有点重复,但根据我的要求和上面的代码似乎不符合我的目的,但让我试试..
  • @Isma 您引用的链接对我的代码没有帮助。需要帮助。
  • a=[] for root, dirs, files in os.walk('.'): dirs[:] = list(filter(lambda x : x != 'folder3', dirs)) for pdf in glob(os.path.join(file[0], '*.txt')): a.append(txt) a 提供空列表作为输出,但还有其他可用文件夹。 @伊斯玛
  • @Isma 我认为for pdf in glob(os.path.join(file[0], '*.txt') 需要修复,以避免挖掘folder3

标签: python python-3.x python-2.7 lambda


【解决方案1】:

以下解决方案似乎有效,排除集中指定的任何目录都将被忽略,扩展集中的任何扩展都将包括在内。

import os

exclude = set(['folder3'])
extensions = set(['.txt', '.dat'])
for root, dirs, files in os.walk('c:/temp/folder', topdown=True):
    dirs[:] = [d for d in dirs if d not in exclude]
    files = [file for file in files if os.path.splitext(file)[1] in extensions]
    for fname in files:
        print(fname)

此代码使用选项topdown=True 来修改docs 中指定的目录名称列表:

当 topdown 为 True 时,调用者可以就地修改目录名列表 (可能使用 del 或 slice 赋值),而 walk() 只会递归 进入名称保留在 dirnames 中的子目录;这可以是 用于修剪搜索

【讨论】:

  • 什么是分割文本?可以为其他文件类型完成吗?
  • 那是获取扩展名。检查上一次编辑,您现在可以指定多个扩展名。
  • os.walk 的文档明确指出,如果 topdown=True(这是默认设置)然后修改 dirs 目录可以达到 OP 的要求。您可能可以在文档中添加引用以澄清这不是意外......
  • 感谢您的详细回答。我发现这也适用于最近的堆栈帖子 for root, dirs, files in os.walk('.'): if "folder3" not in root: for file in files: if file.endswith(".txt"): print (os.path.join(root, file)) 之一。如果我们不得不忽略多个目录,您提供的答案非常有帮助。
  • 是的,目的是 - 如果我的代码在 Desktop 中并且在其中我有多个文件夹及其各自的子文件夹。但让我试一试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
  • 2012-11-19
  • 2015-12-11
  • 2013-03-22
  • 2019-02-05
相关资源
最近更新 更多