This should work:
from __future__ import print_function # => For Python 2.5 - 2.7
import os
def delete_files_with_size(dirname, size):
for root, _, files in os.walk(dirname):
for filename in files:
filepath = os.path.join(root, filename)
if os.path.getsize(filepath) == size:
print('removing {0}'.format(filepath))
os.remove(filepath)
Like you said, os.walk is the way to go for this sort of thing. os.walk
returns a tuple containing the root path, a list of directories, and a list of files. Since we're not interested in directories, we use the conventional _
variable name when unpacking the return value.
Since the filename itself doesn't include the path, you can use os.path.join
with root
and filename
. os.path.getsize will return the size of the file, and os.remove
will delete that file if it matches the size.