List Directories

Different methods for listing folders in a directory.

List directories in Python.

Date Created:Friday December 29th, 2006 03:41 AM
Date Modified:Friday August 01st, 2008 01:18 AM

import os

# dircache.annotate puts the slashes on directories.
>>> a = dircache.listdir('.')
>>> a = a[:] # making a copy of a lets us edit it
>>> dircache.annotate('.',a)
>>> a
['.CFUserTextEncoding', '.DS_Store', '.Trash/', '.bash_history', '.ssh/', '.viminfo', 'Applications/', 'Desktop/', 'Documents/', 'Incomplete/', 'Library/', 'Movies/', 'Music/', 'OngameNetwork/', 'Pictures/', 'Public/', 'Sites/', 'readme.txt', '', 'testing.pyc']

# this makes libraries out of files and folders:
import os
import dircache

folders = {}
files   = {}
list = dircache.listdir('.')
for x in list:
     if os.path.isdir(x): folders[x]=dircache.listdir(x)
     if os.path.isfile(x): files[x]=os.path.getsize(x)

# prints out all contents of folders
for x in folders: print folders[x]

# prints out all files sizes
for x in files: print x, ' ', files[x]

# prints folders
for x in folders:
     for y in folders[x]:
          print x, '/', y