ePub package.opf generator
This is the first pass at a script to generate a basic `package.opf` file for epub3 ebooks using Python 2.X. ## What it does When you run it from the root of your ebook, the script will create a `package.opf` file, populate it with basic metadata as required by the epub3 specification, it will also create metadata and spine sections based on the content of the OEBPS directory. ## How does the script do it The script only uses modules from the default library. I want the a portable script and I don't want to worry whether a module is compatible with 2.X and 3.X, compatible with either version or if uses a different syntax on each version. At the top of the script we use the environment 'shebang' to declare the location of the Python executable without hard coding it. We import the following modules, each for a specific purpose: - **_mimetypes_** to find the mime type of our files automatically - **_glob_** to create the list of files under OEBPS - **_os_** and **_os.path_** to create the items we populate our package file with After loading the modules the first thing we do is initialize our mime-type database. This will make sure, as much as possible, that we match the file with the correct mime-type. We then open our package.opf file in write mode. The last step in this stage is to create the glob expression that will tell the rest of the scripts what files to work with. We are now ready to create the content we'll write to the file. ```python #!/usr/bin/env python import mimetypes import glob import os import os.path # Initialize the mimetypes database mimetypes.init() # Create the package.opf file package = open('package.opf', 'w') # WARNING: This glob will add all files and directories # to the variable. You will have to edit the file and remove # empty directories and the package.opf file reference from # both the manifest and the spine package_content = glob.glob('OEBPS/**/*') ``` The second stage is to create the templates for the XML portions of the package. There are two things to notice with this part. - The XML elements are empty. I only create attributes as necessary - I create static templates and don't use dynamic content because all the modules I found had issues when working with namespaces. The three templates will be used when building the file. ```python template_top = '''