os.walk()

1 PM February 23, 2004

This morning I was writing a script that operates on every html file on my hard disk. I was just going to have my script read the output of ”find . -name ’*.html’”, but then I remembered Python 2.3’s os.walk() function. Here’s the code to find my html files:

import os

def htmlFiles():
for (path, dames, fnames) in os.walk(“C:\\”):
for fn in fnames:
if fn.endswith(”.html”):
yield os.path.join(path, fn)

Very neat.

Update: Added the import and the os.path.join().

By alang | # | Comments (7)
(Posted to Software Development and Python)

Comments

At 15:14, 23 Feb 2004 Daniel B wrote:

Very neat

Sounds like you're writing a virus ;)

(#)
At 22:26, 23 Feb 2004 Greg wrote:

Or using James Orendorff's path module (http://www.jorendorff.com/articles/python/path/):

from path import path

def htmlFiles():
    dir = path('C:\\')
    for fn in dir.walkfiles('*.html'):
        yield fn
(#)
At 07:09, 24 Feb 2004 Alan Green wrote:

Greg: Thanks for the link.

(#)
At 12:06, 24 Feb 2004 Charles Miller wrote:

Ruby: Dir["/**/*.html"].each { |file| ... }

I'm sorry, I couldn't help it :)

(#)
At 13:42, 24 Feb 2004 Alan Green wrote:

Charles: surprised you took so long.

That Ruby snippet looks like cartoon-strip swearing. :)

(#)
At 14:25, 24 Feb 2004 Charles Miller wrote:

http://www.deftcode.com/archives/every_language_war_ever.html

(#)
At 19:58, 30 Oct 2004 sobko wrote:

Bash: find . -name "*mp3" -print

(#)

Add Comment




(Not displayed)






(Leave blank line between paragraphs. URLs converted to links. HTML stripped. Indented source code will be formatted with <pre> tags.)




© 2003-2006 Alan Green