Python script to loop through all files in directory, delete any that are less than 200 kB in size

前端 未结 4 1845
醉话见心
醉话见心 2021-01-31 03:39

I want to delete all files in a folder that are less than 200 kB in size.

Just want to be sure here, when i do a ls -la on my macbook, the file size says 171 or 143, I a

相关标签:
4条回答
  • 2021-01-31 03:55

    You could also use

    import os    
    
    files_in_dir = os.listdir(path_to_dir)
    for file_in_dir in files_in_dir:
        #do the check you need on each file
    
    0 讨论(0)
  • 2021-01-31 04:00

    This does directory and all subdirectories:

    import os, os.path
    
    for root, _, files in os.walk(dirtocheck):
        for f in files:
            fullpath = os.path.join(root, f)
            if os.path.getsize(fullpath) < 200 * 1024:
                os.remove(fullpath)
    

    Or:

    import os, os.path
    
    fileiter = (os.path.join(root, f)
        for root, _, files in os.walk(dirtocheck)
        for f in files)
    smallfileiter = (f for f in fileiter if os.path.getsize(f) < 200 * 1024)
    for small in smallfileiter:
        os.remove(small)
    
    0 讨论(0)
  • 2021-01-31 04:10

    you can also use find

    find /path -type f -size -200k -delete
    
    0 讨论(0)
  • 2021-01-31 04:17

    Generally ls -la is in bytes.

    If you want it in "human readable" form, use the command ls -alh.

    0 讨论(0)
提交回复
热议问题