我正在编写一个脚本,以递归地遍历主文件夹中的子文件夹,并构建一个特定文件类型的列表。我对剧本有点意见。目前设置如下:

for root, subFolder, files in os.walk(PATH):
    for item in files:
        if item.endswith(".txt") :
            fileNamePath = str(os.path.join(root,subFolder,item))

问题是subFolder变量拉入的是子文件夹列表,而不是ITEM文件所在的文件夹。我在考虑之前运行子文件夹的for循环,并加入路径的第一部分,但我想我会仔细检查,看看是否有人有任何建议之前。


当前回答

您应该使用称为root的dirpath。提供了dirnames,因此如果有不希望操作的文件夹,您可以删除它。递归入。

import os
result = [os.path.join(dp, f) for dp, dn, filenames in os.walk(PATH) for f in filenames if os.path.splitext(f)[1] == '.txt']

编辑:

在最近的反对票之后,我突然意识到glob是一个更好的扩展选择工具。

import os
from glob import glob
result = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.txt'))]

还有一个生成器版本

from itertools import chain
result = (chain.from_iterable(glob(os.path.join(x[0], '*.txt')) for x in os.walk('.')))

用于Python 3.4+的Edit2

from pathlib import Path
result = list(Path(".").rglob("*.[tT][xX][tT]"))

其他回答

我将把John La Rooy的列表理解转换为嵌套for,以防其他人理解它有困难。

result = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], '*.txt'))]

应该相当于:

import glob
import os

result = []

for x in os.walk(PATH):
    for y in glob.glob(os.path.join(x[0], '*.txt')):
        result.append(y)

下面是列表理解和函数os的文档。走着走着。

您最初的解决方案几乎是正确的,但是变量“root”在递归遍历时被动态更新。Os.walk()是一个递归生成器。每个元组(root, subFolder, files)都是针对特定的根目录设置的。

i.e.

root = 'C:\\'
subFolder = ['Users', 'ProgramFiles', 'ProgramFiles (x86)', 'Windows', ...]
files = ['foo1.txt', 'foo2.txt', 'foo3.txt', ...]

root = 'C:\\Users\\'
subFolder = ['UserAccount1', 'UserAccount2', ...]
files = ['bar1.txt', 'bar2.txt', 'bar3.txt', ...]

...

我对你的代码做了轻微的调整,以打印一个完整的列表。

import os
for root, subFolder, files in os.walk(PATH):
    for item in files:
        if item.endswith(".txt") :
            fileNamePath = str(os.path.join(root,item))
            print(fileNamePath)

希望这能有所帮助!

编辑:(根据反馈)

OP误解/错误标记了子文件夹变量,因为它实际上是“根”中的所有子文件夹。因为OP,你要执行os。path。Join (str, list, str),这可能不像你预期的那样。

为了帮助增加清晰度,你可以试试这个标签方案:

import os
for current_dir_path, current_subdirs, current_files in os.walk(RECURSIVE_ROOT):
    for aFile in current_files:
        if aFile.endswith(".txt") :
            txt_file_path = str(os.path.join(current_dir_path, aFile))
            print(txt_file_path)

你可以使用glob模块中的“递归”设置来搜索子目录

例如:

import glob
glob.glob('//Mypath/folder/**/*',recursive = True)

第二行将返回该文件夹位置子目录中的所有文件(注意,您需要在文件夹字符串的末尾使用'**/*'字符串来执行此操作)。

如果您特别希望查找子目录深处的文本文件,可以使用

glob.glob('//Mypath/folder/**/*.txt',recursive = True)

如果你不介意安装一个额外的灯光库,你可以这样做:

pip install plazy

用法:

import plazy

txt_filter = lambda x : True if x.endswith('.txt') else False
files = plazy.list_files(root='data', filter_func=txt_filter, is_include_root=True)

结果应该是这样的:

['data/a.txt', 'data/b.txt', 'data/sub_dir/c.txt']

它可以在Python 2.7和Python 3上运行。

Github: https://github.com/kyzas/plazy文件

免责声明:我是plazy的作者。

这不是最python的答案,但我把它放在这里是为了好玩,因为这是递归的一课

def find_files( files, dirs=[], extensions=[]):
    new_dirs = []
    for d in dirs:
        try:
            new_dirs += [ os.path.join(d, f) for f in os.listdir(d) ]
        except OSError:
            if os.path.splitext(d)[1] in extensions:
                files.append(d)

    if new_dirs:
        find_files(files, new_dirs, extensions )
    else:
        return

在我的机器上有两个文件夹,root和root2

mender@multivax ]ls -R root root2
root:
temp1 temp2

root/temp1:
temp1.1 temp1.2

root/temp1/temp1.1:
f1.mid

root/temp1/temp1.2:
f.mi  f.mid

root/temp2:
tmp.mid

root2:
dummie.txt temp3

root2/temp3:
song.mid

假设我想在这两个目录中找到所有。txt和。mid文件,然后我就可以

files = []
find_files( files, dirs=['root','root2'], extensions=['.mid','.txt'] )
print(files)

#['root2/dummie.txt',
# 'root/temp2/tmp.mid',
# 'root2/temp3/song.mid',
# 'root/temp1/temp1.1/f1.mid',
# 'root/temp1/temp1.2/f.mid']