【问题标题】:How to exclude files extension from os.walk如何从 os.walk 中排除文件扩展名
【发布时间】:2016-02-09 21:40:05
【问题描述】:

我想搜索文件,除了那些包含 .txt 文件的文件。怎么做 ? 目前我的代码正在搜索带有 .txt 扩展名的文件。反着怎么办?

src = raw_input("Enter source disk location: ")
src = os.path.abspath(src)
print "src--->:",src
for dir,dirs,_ in os.walk(src, topdown=True):

    file_path = glob.glob(os.path.join(dir,"*.txt"))

【问题讨论】:

    标签: python-2.6 os.walk


    【解决方案1】:

    使用列表理解过滤您的文件:

    for dir, dirs, files in os.walk(src):
        files = [os.path.join(dir, f) for f in files if not f.endswith('.txt')]
    

    我删除了topdown=True 参数;这是默认设置。

    不要将glob.glob()os.walk() 结合使用;这两种方法都在操作系统中查询目录中的文件名。您已经os.walk()的每次迭代的第三个值中拥有这些文件名。

    如果要跳过整个目录,使用any() function查看是否有匹配的文件,然后使用continue忽略此目录:

    for dir, dirs, files in os.walk(src):
        if any(f.endswith('.txt') for f in files):
            continue  # ignore this directory
    
        # do something with the files here, there are no .txt files.
        files = [os.path.join(dir, f) for f in files]
    

    如果您想忽略此目录及其所有后代,请也使用切片分配清除 dirs 变量:

    for dir, dirs, files in os.walk(src):
        if any(f.endswith('.txt') for f in files):
            dirs[:] = []  # do not recurse into subdirectories
            continue      # ignore this directory
    
        # do something with the files here, there are no .txt files.
        files = [os.path.join(dir, f) for f in files]
    

    【讨论】:

    • 如果 .txt 文件存在于子目录中,例如 data----> 文件夹 -----> test.txt 并且我只想排除子目录?
    • @WiktorKostrzewski:所以您想跳过任何包含.txt 文件的目录?
    • 正是 :) 这是我的目标
    • 我只想要其中没有 .txt 的子目录列表。我的目标是过滤这些子目录。此外,我想将它们移动到其他位置。我已经为其中包含 .txt 的目录做了。
    • @WiktorKostrzewski:也有子目录吗?也许收集列表中的目录路径,然后在下一步中移动所有匹配的目录。
    猜你喜欢
    • 2014-04-04
    • 2014-01-04
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    相关资源
    最近更新 更多