Entries For: 2012
- January (1)
2012-01-16
A simple epub file renaming utility
I have a couple of epub files that have random names assigned to them, and I wanted to rename them based on their metadata, in the form Author - Title. Below is what I came up with:
#!/usr/bin/python
from zipfile import ZipFile
import lxml.etree
import os.path
import shutil
import sys
namespaces = {
'u':"urn:oasis:names:tc:opendocument:xmlns:container",
'xsi':"http://www.w3.org/2001/XMLSchema-instance",
'opf':"http://www.idpf.org/2007/opf",
'dcterms':"http://purl.org/dc/terms/",
'calibre':"http://calibre.kovidgoyal.net/2009/metadata",
'dc':"http://purl.org/dc/elements/1.1/",
}
def main():
if len(sys.argv) != 2:
print "Need a path."
sys.exit(1)
fpath = sys.argv[1]
zip = ZipFile(fpath)
meta = zip.read("META-INF/container.xml")
e = lxml.etree.fromstring(meta)
rootfile = e.xpath("/u:container/u:rootfiles/u:rootfile",
namespaces=namespaces)[0]
path = rootfile.get('full-path')
opf = zip.read(path)
e = lxml.etree.fromstring(opf)
title = e.xpath("//dc:title", namespaces=namespaces)[0].text
author = e.xpath("//dc:creator", namespaces=namespaces)[0].text
base = os.path.dirname(fpath)
new_name = "%s - %s.epub" % (author, title)
shutil.move(fpath, os.path.join(base, new_name))
if __name__ == "__main__":
main()