'Replace the keyed message; raise KeyError if it doesn\'t exist.'

def __setitem__(self, key, message):

    path = os.path.join(self._path, str(key))
    try:
        f = open(path, 'rb+')
    except IOError as e:
        if (e.errno == errno.ENOENT):
            raise KeyError(('No    message    with    key:    %s' % key))
        else:
            raise
    try:
        if self._locked:
            _lock_file(f)
        try:
            os.close(os.open(path, (os.O_WRONLY | os.O_TRUNC)))
            self._dump_message(message, f)
            if isinstance(message, MHMessage):
                self._dump_sequences(message, key)
        finally:
            if self._locked:
                _unlock_file(f)
    finally:
        _sync_close(f)
