python - 查找包含两个以特定字符串结尾的文件的所有子文件夹

标签 python python-3.x

所以我有一个文件夹,比如 D:\Tree,它只包含子文件夹(名称可能包含空格)。这些子文件夹包含一些文件 - 并且它们可能包含 "D:\Tree\SubfolderName\SubfolderName_One.txt""D:\Tree\SubfolderName\SubfolderName_Two.txt"形式的文件 (换句话说,子文件夹可能包含两者、一个或两者都不包含)。我需要找到子文件夹包含这两个文件的每次出现,并将它们的绝对路径发送到文本文件(采用以下示例中解释的格式)。考虑 D:\Tree 中的这三个子文件夹:

D:\Tree\Grass contains Grass_One.txt and Grass_Two.txt
D:\Tree\Leaf contains Leaf_One.txt
D:\Tree\Branch contains Branch_One.txt and Branch_Two.txt

考虑到这种结构和上面提到的问题,我希望能够在 myfile.txt 中编写以下几行:

D:\Tree\Grass\Grass_One.txt D:\Tree\Grass\Grass_Two.txt
D:\Tree\Branch\Branch_One.txt D:\Tree\Branch\Branch_Two.txt

如何做到这一点?预先感谢您的帮助!

注意:在 myfile.txt 中,“file_One.txt”位于“file_Two.txt”之前,这一点非常重要

最佳答案

import os

folderPath = r'Your Folder Path'

for (dirPath, allDirNames, allFileNames) in os.walk(folderPath):
    for fileName in allFileNames: 
        if fileName.endswith("One.txt") or fileName.endswith("Two.txt") :
            print (os.path.join(dirPath, fileName)) 
            # Or do your task as writing in file as per your need

希望这有帮助......

关于python - 查找包含两个以特定字符串结尾的文件的所有子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45618185/

相关文章:

excel - 使用Python删除Excel中的重复/重复出现

python - 如何从品脱数量列表中创建 numpy 数组

Python:从 NxM 正态分布中抽取的 NxM 样本数组

python - 如何在Python中使用BeautifulSoup获取带有内部<li>或其他标签文本的外部<li>标签

python - 如何从子进程访问子进程 Popen pass_fds 参数?

python - 没有 tf.keras.backend 的 lambda 层函数定义(Python Keras 包)

python - 从 ReactJS 前端访问 Django MEDIA_URL 和 MEDIA_ROOT setting.py 值

python - maya 的宏工具

python - 通过python在字典内的字典中打印数字

python - 在 python 的 if 语句中分配变量的 c 风格