【问题标题】:Finding the path of a folder with specific characters and latest date in python在python中查找具有特定字符和最新日期的文件夹的路径
【发布时间】:2018-03-27 15:11:30
【问题描述】:

我有一个\\path\\to\\folder,它有很多文件夹,其中prefix 是4MOX_ 和7MOX_,suffix 是Date in MM-DD-YYYY,例如03-08-2017、04-09-2016。下面给出了文件夹的示例集。谁能帮我指出最新日期的文件夹,其中包含4MOX_,以供我进一步分析。

文件夹:

4MOX_06-08-2016 4MOX_07-08-2017 4MOX_12-22-2017 6MOX_06-08-2017 6MOX_07-08-2017 6MOX_12-22-2017

输出:

我需要指出文件夹\\path\\to\\folder\\4MOX_12-22-2017

谁能帮我解决这个问题。

【问题讨论】:

  • 为什么标记为pandas?输入是否存储在数据框中?
  • @Aran-Fey 文件夹中的文件存储在数据框中
  • 另外,请发布您的代码。我们通常希望看到一些证据,证明您已经花了一些时间尝试解决问题,而不仅仅是将您的工作推给互联网上的随机陌生人。
  • all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)] 我已将此作为源,但它是在最后创建日期之前创建的,并且没有找到特定的字符串。
  • 请edit它进入问题。但我想这意味着我们不必使用数据框作为输入? pandas 标签在这里看起来有点不合适。

标签: python date format directory


【解决方案1】:

您可以执行以下步骤:

import os

your_path = '\\path\\to\\folder'

# list all files in the path
lst = os.listdir(your_path)

# find file names which starts with 4MOX
lst = [x for x in lst if x.startswith('4MOX')]

# sort the list to get the file with latest date (from comments)
lst = sorted(lst, key=lambda x: datetime.datetime.strptime(x[-10:], '%m-%d-%Y'), reverse=True)

# create path of the file
os.path.join(your_path, lst[0])

【讨论】:

  • @Manish - Aran 是对的,我确实尝试了其他可行的示例,但在 Aran 提供的示例上它不起作用
  • @Aran-Fey 感谢 aran 提出。我正在修复它。
猜你喜欢
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 2017-11-24
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多