Keep latest file and delete all other

前端 未结 5 1731
盖世英雄少女心
盖世英雄少女心 2021-01-16 08:35

In my folder there are many pdf files with date-timestamp format such as shown in the last. I would like to keep the latest file for the day and delete the rest for that day

5条回答
  •  离开以前
    2021-01-16 08:55

    Your desired list can also be achieved using groupby .

    from itertools import groupby
    from os import listdir,unlink
    
    filtered_list = list()
    names = os.listdir()
    
    for key,group in groupby(names,lambda x : x[:10]): # groups based on the start 10 characters of file
      filtered_list.append([item for item in group][-1]) #picks the last file from the group
    
    print filtered_list
    

提交回复
热议问题