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

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


当前回答

在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):
    # ...

其他回答

最简单最基本的方法:

import os
for parent_path, _, filenames in os.walk('.'):
    for f in filenames:
        print(os.path.join(parent_path, f))

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

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 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):
    # ...

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

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

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

例如:

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

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

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

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