问题描述
假设我有一个包含多个子目录的目录:
Suppose I have a directory that contains multiple subdirectories:
one_meter = r"C:\Projects\NED_1m"
在目录one_meter
中,我想找到所有以'.xml'结尾并包含字符串"_meta"的文件.我的问题是,某些子目录的文件级别为1级,而其他子目录的级别则为2级例如:
Within the directory one_meter
I want to find all of the files that end with '.xml' and contain the string "_meta". My problem is that some of the subdirectories have that file one level donw, while others have it 2 levels downEX:
one_meter > USGS_NED_one_meter_x19y329_LA_Jean_Lafitte_2013_IMG_2015 > USGS_NED_one_meter_x19y329_LA_Jean_Lafitte_2013_IMG_2015_meta.xml
one_meter > NY_Long_Island> USGS_NED_one_meter_x23y454_NY_LongIsland_Z18_2014_IMG_2015 > USGS_NED_one_meter_x23y454_NY_LongIsland_Z18_2014_IMG_2015_meta.xml
我想查看我的主目录(one_meter') and find all of the
_meta.xml files (regardless of the subdirectory) and append them to a list (
one_m_lister = []`).我尝试了以下操作,但未产生任何结果.我在做什么错?
I want to look in my main directory (one_meter') and find all of the
_meta.xmlfiles (regardless of the subdirectory) and append them to a list (
one_m_lister = []`).I tried the following but it doesn't produce any results. What am I doing incorrectly?
one_m_list = []
for filename in os.listdir(one_meter):
if filename.endswith(".xml") and "_meta" in filename:
print(filename)
one_m_list.append(filename)
推荐答案
@JonathanDavidArndt的回答很好,但已经过时了.从Python 3.5开始,您可以使用 pathlib.Path.glob
在任何子目录中搜索模式.
The answer of @JonathanDavidArndt is good but quite outdated. Since Python 3.5, you can use pathlib.Path.glob
to search a pattern in any subdirectory.
例如:
import pathlib
destination_root = r"C:\Projects\NED_1m"
pattern = "**/*_meta*.xml"
master_list = list(pathlib.Path(destination_root).glob(pattern))
这篇关于如何在多级子目录中查找文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!