This post originated from an RSS feed registered with Python Buzz
by Jarno Virtanen.
Original Post: The nicety of the path module
Feed Title: Python owns us
Feed URL: http://sedoparking.com/search/registrar.php?domain=®istrar=sedopark
Feed Description: A weblog about Python from the view point of Jarno Virtanen.
A co-worker of mine wanted to know the amount of files in directories,
recursively from a certain directory. He suspected that there is a
find one-liner that could do it, but failing to figure
that out, he decided to use Python. Now, I haven't seen his solution,
but given that he probably used the standard library
os.path.walk and the like, I bet it's a bit more
complicated than the following code that uses Jason Orendorff's path
module (and additionally sorts the output based on the amount of files):
import sys
from path import path
# the path that we start recursing from
root = path(sys.argv[1])
directory_list = []
# iterate recursively through the directories and count the files
for directory in root.walkdirs():
directory_list.append((len(directory.files()), directory))
# sort it
directory_list.sort()
# .. and display the list
for count, directory in directory_list:
print '%5d %s' % (count, directory)
I want my Python to play nicely with files and directories and
Orendorff's path module makes it a lot easier.