Skip to content

Instantly share code, notes, and snippets.

@showell
Created November 11, 2012 02:38
Show Gist options
  • Save showell/4053453 to your computer and use it in GitHub Desktop.
Save showell/4053453 to your computer and use it in GitHub Desktop.
python: file system abstracted as dictionary
import glob
import os
class Directory:
def __init__(self, path = '/'):
self.path = path
def __getitem__(self, key):
fn = os.path.join(self.path, key)
if os.path.exists(fn):
return File(fn)
else:
raise IndexError
def __str__(self):
return 'Directory for %s' % self.path
def __iter__(self):
def child(fn):
path = os.path.join(self.path, fn)
return File(path)
return (child(fn) for fn in os.listdir(self.path))
class UnreadableFile:
def __init__(self, fn):
self.fn = fn
def __str__(self):
return 'unreadable file %s' % self.fn
def File(fn):
if os.path.isdir(fn):
return Directory(fn)
else:
try:
return open(fn)
except:
return UnreadableFile(fn)
root_dir = Directory('/')
for fn in root_dir:
print fn
log = root_dir['var']['log']['system.log']
print next(log).strip()
print next(log).strip()
print next(log).strip()
print next(log).strip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment