简体   繁体   English

使用 python 找到最近日期的 csv

[英]Using python to find the csv with most recent date

I've used an answer to get a list of files in a directory, this looks like:我使用答案来获取目录中的文件列表,如下所示:

['name1_2020-06-25.csv','name1_2020-06-24.csv','name1_2020-06-23.csv','name1_2020-06-22.csv','name_2_2020-06-25.csv','name_2_2020-06-24.csv','name_2_2020-06-23.csv','name_2_2020-06-22.csv']

I would like to find a way of selecting the name1 file with the most recent date.我想找到一种方法来选择具有最近日期的name1文件。

First, you can use the string method startswith() (docs here ) to pick out the out the ones that have the right name.首先,您可以使用字符串方法startswith()此处的文档)来挑选出具有正确名称的那些。 You do not need regex here since the names are at the beginning.您不需要正则表达式,因为名称在开头。

Then since the dates are structured nicely as YYYY-MM-DD you can sort the resulting list using sort() or sorted() (docs here ) to get the most recent date.然后,由于日期的结构很好地为 YYYY-MM-DD,因此您可以使用sort()sorted()此处的文档)对结果列表进行排序以获得最新日期。

Something like this:像这样的东西:

def find_most_recent(file_list, prefix):
    s_list = sorted([fname for fname in file_list if fname.startswith(prefix)])
    return s_list[-1]

This uses list comprehension with an if clause (docs here ) to create a new list filtered to be just the file names starting with the passed in prefix.这使用带有if子句的列表推导( 此处的文档)来创建一个新列表,该列表被过滤为仅以传入前缀开头的文件名。 Then that list is sorted by passing it to sorted() .然后将该列表通过传递给sorted()进行排序。

I did not bother with reversing the sort since it is just as easy to pick off the last entry in the list (using the -1 index on the s_list), but you could if you wanted to by using the option reverse=True on sorted() .我没有为反转排序而烦恼,因为选择列表中的最后一个条目同样容易(使用 s_list 上的 -1 索引),但如果你想使用选项reverse=True on sorted()也可以sorted()

Note that startswith() would have a problem here if the prefix/name could also be a substring of another valid name, but you indicated that this was not an issue and so it could be ignored for this use case.请注意,如果前缀/名称也可能是另一个有效名称的 substring,则startswith()在这里会出现问题,但您指出这不是问题,因此对于此用例可以忽略它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM