DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Comparing Path.py With Os.path

02.12.2006
| 4755 views |
  • submit to reddit
        Taken from Simon Willson's <a href=http://simon.incutio.com/archive/2003/01/22/pythonPathModule>blog post</a>.
# with os.path.walk
def delete_backups(arg, dirname, names):
    for name in names:
        if name.endswith('~'):
            os.remove(os.path.join(dirname, name))

os.path.walk(os.environ['HOME'], delete_backups, None)

# with os.path, if (like me) you can never remember how os.path.walk works
def walk_tree_delete_backups(dir):
    for name in os.listdir(dir):
        path = os.path.join(dir, name)
        if os.path.isdir(path):
            walk_tree_delete_backups(path)
        elif name.endswith('~'):
            os.remove(path)

walk_tree_delete_backups(os.environ['HOME'])

# with path
dir = path(os.environ['HOME'])
for f in dir.walk():
    if f.isfile() and f.endswith('~'):
        os.remove(f)