【问题标题】:How to take information from a filename, and divide it up into several parts to save in a list如何从文件名中获取信息,并将其分成几个部分以保存在列表中
【发布时间】:2023-03-26 09:28:01
【问题描述】:

我需要获取这部分代码并将其转换为一个函数,该函数将从目录中 .h5 文件的文件名中获取信息。我对 python 很陌生,所以希望我在这里的解释是有意义的。下面是代码,下面是需要解析的数据文件名示例。

atl06_dir = 'ATL06 files'
filenames = glob.glob(atl06_dir + '/*h5')
year_selected = 2019
filenames_selected = list()
for filename in filenames:
   product, year, month, day, hour, minute, second, track, cycle, granule, release, version = icesat2_data_utils.h5FilenameParts(os.path.basename(filename)) 
#need to replace this line with a function that grabs from the filename. This one does not work
   if int(year) == year_selected: 
      filenames_selected.append(filename) 

如何让此部分读取 .h5 文件的文件名并根据名称中的分隔输出名称的不同部分,您可以在此处的示例文件名中看到:

ATL06_[yyyymmdd][hhmmss][ttttccss][vvv_rr].h5

我觉得我可以通过要求它读取名称中的某些字符来走上正确的道路,例如:

# product ATL06 = 0 to 5
# year yyyy = indexes 8 to 12
# month mm = 12 to 14
# day dd = 14 to 16
# hour hh = 18 to 20
# minute mm = 20 to 22
# second ss = 22 to 24
# Reference ground track tttt = 27 to 31
# cycle cc = 31 to 33
# orbital segment ss = 33 to 35
# version vvv = 38 to 44

【问题讨论】:

  • 请注意,glob.glob() 创建了一个文件名列表。您可以使用迭代器版本避免这种情况:glob.iglob()。您修改后的for 循环看起来像这样for filename in glob.iglob(atl06_dir + '/*h5')

标签: python python-3.x filenames glob h5py


【解决方案1】:

您可以根据您的要求对其进行切片,例如,

string ="ATL06_[yyyymmdd][hhmmss][ttttccss][vvv_rr].h5"
product = string[0:5]

要提取[] 中的内容,可以使用regex 模块:

import re
string ="ATL06_[yyyymmdd][hhmmss][ttttccss][vvv_rr].h5"
re.findall('\[(.*?)\]',string)

这会返回一个匹配字符串的列表,:

['yyyymmdd', 'hhmmss', 'ttttccss', 'vvv_rr']

并且这个字符串中的每个元素都是一个列表,如果需要可以单独切片

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多