Created
November 11, 2012 02:38
-
-
Save showell/4053453 to your computer and use it in GitHub Desktop.
python: file system abstracted as dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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