Keep latest file and delete all other

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

    Sort the list and delete files if the next file in the list is on the same day,

    import glob
    import os
    files = glob.glob("*.pdf")
    files.sort()
    
    for ifl, fl in enumerate(files[:-1]):
        if files[ifl+1].startswith(fl[:10]):    #Check if next file is same day
            os.unlink(fl)                       # It is - delete current file
    

    Edit:

    As the OPs question became clearer it became evident that not just the last file of the list is required, but the latest file of each day - to achieve this I included a "same day" conditioned unlinking.

提交回复
热议问题