Skip to content

Instantly share code, notes, and snippets.

@lxneng
Created July 20, 2012 04:48
Show Gist options
  • Save lxneng/3148756 to your computer and use it in GitHub Desktop.
Save lxneng/3148756 to your computer and use it in GitHub Desktop.

DictMixin is pretty cool. You just need to define getitem, setitem, delitem and keys and then you get a full dictionary interface (everything else being defined in terms of those methods). For example:

from UserDict import DictMixin

class Filesystem(DictMixin):
    def __init__(self, dir):
        self.dir = dir
    def __getitem__(self, path):
        new_path = os.path.join(self.dir, path)
        if not os.path.exists(new_path):
            raise KeyError(new_path)
        if os.path.isdir(new_path):
            return self.__class__(new_path)
        with open(new_path, 'rb') as fp:
            return fp.read()
    def __setitem__(self, path, value):
        try:
            del self[path]
        except KeyError:
            pass
        new_path = os.path.join(self.dir, path)
        if isinstance(value, (dict, DictMixin)):
            os.mkdir(new_path)
            self[path].update(value)
        else:
            with open(new_path, 'wb') as fp:
                fp.write(new_path)
    def __delitem__(self, path):
        new_path = os.path.join(self.dir, path)
        if not os.path.exists(new_path):
            raise KeyError(new_path)
        if os.path.isdir(new_path):
            shutil.rmtree(new_path)
        else:
            os.unlink(new_path)
    def keys(self):
        return os.listdir(self.dir)

Now you have a dictionary that mirrors the filesystem. To delete all files in the current directory:

Filesystem('.').clear()

To write a bunch of files at once:

Filesystem('.').update({"test.txt": "hi!"})

To create a subdirectory of files:

Filesystem('.')['new_dir'] = {"test.txt": "hi!"}

To recursively copy ./old_dir/ to ./new_dir/:

here = Filesystem('.')
here['new_dir'] = here['old_dir']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment