Iterating Through Directories And Checking The File's Size
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 o
Solution 1:
Try this:
import osfor root, dirs, files inos.walk('/path/to/dir', topdown=False):
for name in files:
f = os.path.join(root, name)
ifos.path.getsize(f) == filesize:
os.remove(f)
Solution 2:
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 inos.walk(dirname):
for filename in files:
filepath = os.path.join(root, filename)
ifos.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.
Post a Comment for "Iterating Through Directories And Checking The File's Size"