在文件路径列表中查找以相同字符串开头的python文件

2024-06-03 03:24:14 发布

您现在位置:Python中文网/ 问答频道 /正文

[' D:\\2019-09-06_ECOSTRESS_L3_ET_PT-JPL_06627_012_20190906T075008_0601_02_ETinst.tif', ' D:\\2019-09-06_ECOSTRESS_L3_ET_PT-JPL_06627_012_20190906T075008_0601_02_ETinstUncertainty.tif', ' D:\\2019-09-06_ECOSTRESS_L3_ET_PT-JPL_06627_013_20190906T075100_0601_01_ETinst.tif', ' D:\\2019-09-06_ECOSTRESS_L3_ET_PT-JPL_06627_013_20190906T075100_0601_01_ETinstUncertainty.tif', ' D:\\2019-09-14_ECOSTRESS_L3_ET_PT-JPL_06749_010_20190914T043343_0601_02_ETinst.tif', ' D:\\2019-09-14_ECOSTRESS_L3_ET_PT-JPL_06749_010_20190914T043343_0601_02_ETinstUncertainty.tif', ' D:\\2019-10-29_ECOSTRESS_L3_ET_PT-JPL_07451_013_20191029T104129_0601_01_ETinst.tif', ' D:\\2019-10-29_ECOSTRESS_L3_ET_PT-JPL_07451_013_20191029T104129_0601_01_ETinstUncertainty.tif', ' D:\\2019-11-13_ECOSTRESS_L3_ET_PT-JPL_07680_016_20191113T050013_0601_01_ETinst.tif', ' D:\\2019-11-13_ECOSTRESS_L3_ET_PT-JPL_07680_016_20191113T050013_0601_01_ETinstUncertainty.tif', ' D:\\2019-11-13_ECOSTRESS_L3_ET_PT-JPL_07680_017_20191113T050105_0601_01_ETinst.tif', ' D:\\2019-11-13_ECOSTRESS_L3_ET_PT-JPL_07680_017_20191113T050105_0601_01_ETinstUncertainty.tif', ' D:\\2019-12-17_ECOSTRESS_L3_ET_PT-JPL_08207_001_20191217T034051_0601_01_ETinst.tif', ' D:\\2019-12-17_ECOSTRESS_L3_ET_PT-JPL_08207_001_20191217T034051_0601_01_ETinstUncertainty.tif']

我在python列表中有一个文件路径列表。我想查找属于同一日期的所有文件,例如4个文件的名称以'2019-09-06'开头。如何将此列表划分为较小的列表,每个列表的开头都有相同日期的文件?我不知道常见的日期,所以解决方案应该能够动态地找到它们


Tags: 文件路径名称pt列表动态解决方案jpl
2条回答

您可以使用字典来存储与密钥日期相同的文件

from collections import defaultdict
dates=defaultdict(list)
for path in paths:
    key,val=path[4:14],path[14:]
    dates[key].append(val)

import re
paths = [' D:\\2019-09-06_ECOSTRESS_L3_ET_PT-JPL_06627_012_20190906T075008_0601_02_ETinst.tif', ' D:\\2019-09-06_ECOSTRESS_L3_ET_PT-JPL_06627_012_20190906T075008_0601_02_ETinstUncertainty.tif', ' D:\\2019-09-06_ECOSTRESS_L3_ET_PT-JPL_06627_013_20190906T075100_0601_01_ETinst.tif', ' D:\\2019-09-06_ECOSTRESS_L3_ET_PT-JPL_06627_013_20190906T075100_0601_01_ETinstUncertainty.tif', ' D:\\2019-09-14_ECOSTRESS_L3_ET_PT-JPL_06749_010_20190914T043343_0601_02_ETinst.tif', ' D:\\2019-09-14_ECOSTRESS_L3_ET_PT-JPL_06749_010_20190914T043343_0601_02_ETinstUncertainty.tif', ' D:\\2019-10-29_ECOSTRESS_L3_ET_PT-JPL_07451_013_20191029T104129_0601_01_ETinst.tif', ' D:\\2019-10-29_ECOSTRESS_L3_ET_PT-JPL_07451_013_20191029T104129_0601_01_ETinstUncertainty.tif']
arrays=[]
dates = input().split(" ")
#input dates
for  path in paths :
      array = []
      for date in dates:                
            match = re.search(date,path)
            if match is not None:
                   array.append(path)
      arrays.append(array)

我使用正则表达式对其进行排序。如果愿意,可以将值输入到日期数组中,但这会提供一个已排序列表的列表

相关问题 更多 >