【问题标题】:Group files into lists according to their date in the filename using Python使用 Python 根据文件名中的日期将文件分组到列表中
【发布时间】:2020-01-28 20:33:52
【问题描述】:

我在一个目录中有几个文件。在所有这些文件名中都是“隐藏”的日期。例如,一小段摘录如下所示:

HLS.S30.T34JDN.2018301.v1.4.hdf
HLS.S30.T34JEN.2018308.v1.4.hdf
HLS.S30.T34JDN.2018311.v1.4.hdf      
HLS.S30.T34JEP.2018293.v1.4.hdf

日期是一年中的儒略日。在这种情况下,它是 301、308、311 和 293。目录中有同一天的文件,我想使用 Python 将它们组合到单独的列表中。

我认为这不是太难,但我对解析(?)/正则表达式了解不多。

【问题讨论】:

  • 为什么需要正则表达式? line.split('.')[3][4:] 做到了
  • 太棒了!非常感谢!你能用语言向我解释一下那里发生了什么吗?

标签: python regex string datetime parsing


【解决方案1】:

使用os.listdir() 方法(documentation here),您可以获得所有文件名的列表作为字符串,然后使用字符串解析提取日期。例如:

for filename in os.listdir(path):
    year = int(filename[15:19])
    day = int(filename[19:22])
    # then sort as needed, eg:
    lst.append(path+filename)
    # Using path+filename gives the full path to the file needed,
    # whereas filename is just the name of the file as a string.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多