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

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循环,并加入路径的第一部分,但我想我会仔细检查,看看是否有人有任何建议之前。


当前回答

此函数将递归地将文件放入列表中。

import os


def ls_files(dir):
    files = list()
    for item in os.listdir(dir):
        abspath = os.path.join(dir, item)
        try:
            if os.path.isdir(abspath):
                files = files + ls_files(abspath)
            else:
                files.append(abspath)
        except FileNotFoundError as err:
            print('invalid directory\n', 'Error: ', err)
    return files

其他回答

在Python 3.5更改:支持使用" ** "的递归glob。

Glob.glob()有一个新的递归参数。

如果你想获取my_path下的每个.txt文件(递归地包括subdirs):

import glob

files = glob.glob(my_path + '/**/*.txt', recursive=True)

# my_path/     the dir
# **/       every file and dir under my_path
# *.txt     every file that ends with '.txt'

如果你需要一个迭代器,你可以使用iglob作为替代:

for file in glob.iglob(my_path, recursive=True):
    # ...

递归是Python 3.5中的新功能,所以它在Python 2.7中不起作用。下面是一个使用r个字符串的例子,你只需要提供路径,就像Win, Lin,…

import glob

mypath=r"C:\Users\dj\Desktop\nba"

files = glob.glob(mypath + r'\**\*.py', recursive=True)
# print(files) # as list
for f in files:
    print(f) # nice looking single line per file

注意:它将列出所有文件,无论它应该有多深。

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

例如:

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

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

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

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

您应该使用称为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]"))

新的pathlib库将其简化为一行:

from pathlib import Path
result = list(Path(PATH).glob('**/*.txt'))

你也可以使用生成器版本:

from pathlib import Path
for file in Path(PATH).glob('**/*.txt'):
    pass

这将返回Path对象,您可以将其用于几乎任何事情,或者通过file.name获取文件名作为字符串。