Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 am assuming this is kb correct?

like image 225
Blankman Avatar asked Oct 16 '10 01:10

Blankman


People also ask

How do I loop multiple files in a directory in Python?

Import the os library and pass the directory in the os. listdir() function. Create a tuple having the extensions that you want to fetch. Through a loop iterate over all the files in the directory and print the file having a particular extension.


2 Answers

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)
like image 184
hughdbrown Avatar answered Oct 08 '22 20:10

hughdbrown


you can also use find

find /path -type f -size -200k -delete
like image 31
ghostdog74 Avatar answered Oct 08 '22 20:10

ghostdog74