简体   繁体   English

Python 搜索包含特定子文件夹名称的子文件夹中的所有文件

[英]Python search all files in subfolders containing specific subfolder name

For example, I have 3 subfolders in the root directory and 2 subfolders in each subfolders, as shown below:比如我根目录下有3个子文件夹,每个子文件夹下有2个子文件夹,如下图:

C:/main/canada/May 2022
C:/main/canada/Jun 2022
C:/main/usa/May 2022
C:/main/usa/Jun 2022
C:/main/mexico/May 2022
C:/main/mexico/Jun 2022

I am hoping to only scan for files in subfolders with name contains substring 'May'.我希望只扫描名称包含 substring 'May' 的子文件夹中的文件。

I am beginner and tried os, glob, pathlib, but don't think my thinking is correct.我是初学者,尝试过 os、glob、pathlib,但不认为我的想法是正确的。

You could try first globbing for subdirectories that match using glob.glob , and then finding their parents using pathlib.Path.parent :您可以尝试首先使用glob.glob查找匹配的子目录,然后使用pathlib.Path.parent查找它们的父目录:

import glob
import pathlib
for subdir in glob.glob("C:/main/*/*May*"):
    print(pathlib.Path(subdir).parent)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python:通过子文件夹名称重命名子文件夹中的文件 - python: rename files in subfolders by subfolder name Python:如何在ALL文件,文件夹和子文件夹的名称中用下划线替换空格? - Python: How to replace whitespaces by underscore in the name of ALL files, folders and subfolders? 使用Python中子文件夹的名称为每个子文件夹创建空文件 - Make empty file for each subfolder using subfolders' name in Python Python-遍历目录中的子文件夹和文件,而不会忽略该子文件夹 - Python - loop through subfolders and files in a directory without ignoring the subfolder 在子文件夹python中读取所有文件 - read all files in a subfolder python 如何将子文件夹中所有特定文件类型的文件重命名为具有相同文件扩展名但文件名相同的名称 - How to rename all specific filetypes of files within subfolders to name with same file extension but same file name Python:搜索特定字符串的文件文件夹,然后列出包含它的所有文件 - Python: Scour a folder of files for a specific string, then list all the files containing it 使用Python计算所有文件夹/子文件夹中的所有文件 - Count all files in all folders/subfolders with Python Python如何访问子文件夹的子文件夹 - Python how to access subfolder of subfolders 在目录python中搜索所有具有相同名称的文件 - Search all files with same name in a directory python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM