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

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中的新功能,所以它在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”在递归遍历时被动态更新。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)

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

最简单最基本的方法:

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

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