2

I want to iterate through directories, and subdirectories, and check each file for a filesize. If it matches the defined filesize, it will be deleted.

I know, that i have to use os.walk, but i'm not quite sure, in which way.

The code i used for directory listing is :

import os
path = "C:\\Python27"
i=0
for (path,dirs,files) in os.walk(path):
    print files
    i=i+1
    if i>10:
        break
Nick Craig-Wood
  • 52,955
  • 12
  • 126
  • 132
Robert Shane
  • 73
  • 1
  • 2
  • 5

2 Answers2

3

Try this:

import os

for root, dirs, files in os.walk('/path/to/dir', topdown=False):
    for name in files:
        f = os.path.join(root, name)
        if os.path.getsize(f) == filesize:
            os.remove(f)
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Thanks a lot. It worked! What if i also wanted to check for a filename in the directory same as the directory name. Suppose, checking a file named mydir.txt inside the directory mydir. – Robert Shane May 12 '12 at 17:17
  • @RobertShane it's all the same, add another condition something like `if root.endswith(name[:name.rindex('.')]):` – Óscar López May 12 '12 at 17:31
1

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.

Brian Gesiak
  • 6,648
  • 4
  • 35
  • 50