Skip to content

Instantly share code, notes, and snippets.

@vpayno
Created October 7, 2013 06:48
Show Gist options
  • Select an option

  • Save vpayno/6863473 to your computer and use it in GitHub Desktop.

Select an option

Save vpayno/6863473 to your computer and use it in GitHub Desktop.
Python Cheat Sheets - File Systems

Python Cheat Sheets

by Victor Payno

File Systems

Traverse a file system

import os
import strings

def fswalk(dirpath):
    os.chdir(dirpath)
    dirs = []
    files = []
    for item in os.listdir('.'):
        if os.path.isdir(item):
            dirs.append(item)
        else:
            files.append(item)
    dirs.sort()
    files.sort()
    print "\nCurrent Path:", dirpath, "\n\n"
    print "Directories:", string.replace(str(dirs)[1:-1], "'", ""), "\n\n"
    print "Files:", string.replace(str(files)[1:-1], "'", ""), "\n\n"
    for dir in dirs:
        curdir = os.path.realpath(os.path.curdir)
        fswalk(dir)
        os.chdir(curdir)
fswalk('.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment