FLamparski

fixed directory scanner thing

Mar 22nd, 2013
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. import os, stat
  2.  
  3. def flat_walk(root):
  4.     """Look at a single level of the filesystem and return
  5.    a os.walk-style tuple listing subdirectories and individual files
  6.    in root. Also includes a realpath() on starting path
  7.    because why the hell not.
  8.    """
  9.     inodes = os.listdir(root)
  10.     dirs = []
  11.     files = []
  12.     for inode in inodes:
  13.         nodestat = os.stat(os.path.join(root, inode))
  14.         if stat.S_ISDIR(nodestat.st_mode):
  15.             dirs.append(inode)
  16.         else:
  17.             files.append(inode)
  18.     return os.path.realpath(root), dirs, files
  19.  
  20. def build_filesystem(root):
  21.     """Build a dictionary which contains the filesystem structure from a
  22.    given starting path root.
  23.    """
  24.     dirdict = {}
  25.     path, dirs, files = flat_walk(root)
  26.     for subdir in dirs:
  27.         dirdict[subdir] = build_filesystem(os.path.join(path, subdir))
  28.     for leaf in files:
  29.         dirdict[leaf] = os.path.join(path, leaf)
  30.     return dirdict
Advertisement
Add Comment
Please, Sign In to add comment