<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def to_directory(self, directory, force=False):
 """Write this security object to a directory. Parameters directory : str The directory to write the configuration to. force : bool, optional If security credentials already exist at this location, an error will be raised by default. Set to True to overwrite existing files. Returns ------- security : Security A new security object backed by the written files. """

        self._validate()

        # Create directory if it doesn't exist
        makedirs(directory, exist_ok=True)

        cert_path = os.path.join(directory, 'skein.crt')
        key_path = os.path.join(directory, 'skein.pem')
        cert_bytes = self._get_bytes('cert')
        key_bytes = self._get_bytes('key')

        lock_path = os.path.join(directory, 'skein.lock')
        with lock_file(lock_path):
            for path, name in [(cert_path, 'skein.crt'), (key_path, 'skein.pem')]:
                if os.path.exists(path):
                    if force:
                        os.unlink(path)
                    else:
                        msg = ("%r file already exists, use `%s` to overwrite" %
                               (name, '--force' if context.is_cli else 'force'))
                        raise context.FileExistsError(msg)

            flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
            for path, data in [(cert_path, cert_bytes), (key_path, key_bytes)]:
                with os.fdopen(os.open(path, flags, 0o600), 'wb') as fil:
                    fil.write(data)

        return Security(cert_file=cert_path, key_file=key_path)