使用os.walk方法获取包含两种类型文件的目录路径

时间:2017-01-01 15:02:54

标签: python python-2.7 os.walk

我想在Python 2.7中使用docx。walk方法列出包含os()个文件的所有文件夹。我设法使用下面编写的代码执行此操作,但我想知道是否可以限制此列表以仅显示包含两个特定文件类型的文件夹(例如" docx"和" pdf& #34;?)

import os
import walk

a = open("output.txt", "w")
for path, subdirs, files in os.walk(r'C:\Users\Stephen\Desktop'):
    for filename in files:
        if filename.endswith(('.docx')):
            f = os.path.join(path, filename)
            a.write(str(f) + os.linesep) 

2 个答案:

答案 0 :(得分:2)

只需跳过至少没有这两个扩展名的目录;每个目录文件列表是有限的,因此使用any()来测试特定扩展名是很便宜的:

for path, subdirs, files in os.walk(r'C:\Users\Stephen\Desktop'):
    if not (any(f.endswith('.pdf') for f in files) and 
            any(f.endswith('.docx') for f in files)):
        # no PDF or Word files here, skip
        continue
    # directory contains *both* PDF and Word documets

当要测试的扩展程序列表变得更长时,您可能只想创建一组所有可用扩展程序:

for path, subdirs, files in os.walk(r'C:\Users\Stephen\Desktop'):
    extensions = {os.path.splitext(f)[-1] for f in files}
    if not extensions >= {'.pdf', '.docx', '.odt', '.wpf'}:
        # directory doesn't contain *all* required file types 
        continue

>=测试右手集是左侧的子集(因此extensionssuperset of the right-hand set);所以extensions 至少包含右边所有扩展名的所有内容:

>>> {'.foo', '.docx', '.pdf', '.odt'} >= {'.pdf', '.docx', '.odt', '.wpf'}  # missing .wpf
False
>>> {'.foo', '.wpf', '.docx', '.pdf', '.odt'} >= {'.pdf', '.docx', '.odt', '.wpf'} # complete
True

答案 1 :(得分:0)

此?

import os

a = open("output.txt", "w")
for path, subdirs, files in os.walk(r'C:\Users\Stephen\Desktop'):
    docx = False
    pdf = False
    rest = True
    for filename in files:
        if filename.endswith(('.docx')):
            docx = True
        elif filename.endswith(('.pdf')):
            pdf = True
        else:
            rest = False
            break
    if docx and pdf and rest:
        f = os.path.join(path, filename)
        a.write(str(f) + os.linesep)