Keep latest file and delete all other

前端 未结 5 1737
盖世英雄少女心
盖世英雄少女心 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:51

    The following snippet works with the test case given.

    files = os.listdir(".")
    days = set(fname[8:10] for fname in files)
    
    for d in days:
        f = [i for i in files if i[8:10] == d]
        for x in sorted(f)[:-1]:
            os.remove(x)
    

提交回复
热议问题