Keep latest file and delete all other

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

    Using dictionary You can keep one value. This can be dirty and quickest solution, maybe not the best.

    #!/usr/bin/env python
    import os
    import datetime
    import stat
    import shutil
    
    filelist=[]
    lst=[]
    dc={}
    
    os.chdir(".")
    for files in os.listdir("."):
        if files.endswith(".pdf"):
            lst.append(files)
    
    for x in lst:
        print x[0:10].replace("-","")
        dc[int(x[0:10].replace("-",""))]=x
    
    a = dc.items()
    flist=[]
    for k, v in a:
        flist.append(v)
    
    dir="tmpdir"    
    if not os.path.exists(dir):
        os.makedirs(dir)
    
    from shutil import copyfile
    for x in flist:
        print x
        copyfile(x, dir + "/" + x)
    
    #os.chdir(".")
    for files in os.listdir("."):
        if files.endswith(".pdf"):
                os.unlink(files)
    
    os.chdir("./tmpdir")
    for files in os.listdir("."):
        if files.endswith(".pdf"):
            copyfile(files, "../"+files)
    
    os.chdir("../")
    shutil.rmtree(os.path.abspath(".")+"/tmpdir")
    

提交回复
热议问题