I've taken some of the comments here and provided a Jupyter notebook that does this for a backup of say a Books directory:
import pathlib
import glob
import os
import zipfile
# Extract the relevant components of a full path
def pathComponents(fullpath):
path = pathlib.Path(fullpath)
name = path.name
stem = path.stem
suffix = path.suffix
parent = path.parent
return name, stem, suffix, parent
# Get directories in your path that have a .epub suffix
def getePubDirs(path):
epubSearch = os.path.join(path, "*" + "." + "epub")
eDirs=[]
for p in glob.glob(epubSearch):
if (os.path.isdir(p)): # Only if it's an epub directory
eDirs.append(p)
return eDirs
def createZipFile(fname, files):
zFile = zipfile.ZipFile(fname, mode='w', compression=zipfile.ZIP_DEFLATED)
for f in files:
zFile.write(f)
zFile.close()
def convertDirToePub(dirname):
name, stem, suffix, parent = pathComponents(dirname) # get dirname details
newdirname = zFile = str(parent) + "/" + name + ".ori"
zFile = str(parent) + "/" + stem + ".epub"
os.rename(dirname,newdirname) # rename the epub dir so the epub can take its old name
# get all the files within the epub directory
os.chdir(newdirname) # We need to be in directory so the resultant epub paths are correct
everything = [os.path.join(r,file) for r,d,f in os.walk(".") for file in f]
createZipFile(zFile, everything) # Create a zip file containing all those files
os.chdir(parent)
dirtoconvert='/Users/<username>/tmp/Booksdir'
eDirs = getePubDirs(dirtoconvert)
totalDirs=len(eDirs)
print(totalDirs, "docs to convert")
ctr=1
for i in eDirs:
print(ctr, "of", totalDirs, ": Converting ", i)
convertDirToePub(i)
ctr = ctr + 1
print("Done!")