<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_file(package, directory):
 """Write the package to the given ``directory``. Returns the OPF filename. """

        opf_filepath = os.path.join(directory, package.name)

        # Create the directory structure
        for name in ('contents', 'resources',):
            path = os.path.join(directory, name)
            if not os.path.exists(path):
                os.mkdir(path)

        # Write the items to the filesystem
        locations = {}  # Used when rendering
        for item in package:
            if item.media_type == 'application/xhtml+xml':
                base = os.path.join(directory, 'contents')
            else:
                base = os.path.join(directory, 'resources')
            filename = item.name
            filepath = os.path.join(base, filename)
            locations[item] = os.path.relpath(filepath, directory)
            with open(filepath, 'wb') as item_file:
                item_file.write(item.data.read())

        # Write the OPF
        template = jinja2.Template(OPF_TEMPLATE,
                                   trim_blocks=True, lstrip_blocks=True)
        with open(opf_filepath, 'wb') as opf_file:
            opf = template.render(package=package, locations=locations)
            if not isinstance(opf, bytes):
                opf = opf.encode('utf-8')
            opf_file.write(opf)

        return opf_filepath