Skip to content

Instantly share code, notes, and snippets.

@sanghviharshit
Created March 22, 2022 05:29
Show Gist options
  • Save sanghviharshit/99b5cdf9b23c3f02d34157a0a8bd3e5b to your computer and use it in GitHub Desktop.
Save sanghviharshit/99b5cdf9b23c3f02d34157a0a8bd3e5b to your computer and use it in GitHub Desktop.
Batch creates cbz files for comic book reader from a directory containing directories of jpgs. e.g. downloaded collections using Tachiyomi mobile app.
from typing import List
from zipfile import ZipFile
import glob
import os
from os.path import basename, dirname, exists
# Zip the files from given directory that matches the filter
def zipFilesInDir(dirName, zipFileName, filter):
print("===Creating CBZ from " + dirName + ": " + zipFileName)
# create a ZipFile object
with ZipFile(zipFileName, 'w') as zipObj:
# Iterate over all the files in directory
for folderName, subfolders, filenames in os.walk(dirName):
for filename in filenames:
if filter(filename):
# create complete filepath of file in directory
filePath = os.path.join(folderName, filename)
# Add file to zip
zipObj.write(filePath, basename(filePath))
zipObj.close()
def main():
importDirName = '/Volumes/home/Drive/Comics/Tachiyomi Originals'
exportDirName = '/Volumes/home/Drive/Tachiyomi'
for (dirpath, dirnames, filenames) in os.walk(importDirName):
unprocessed = False
for filename in filenames:
if filename.endswith('.jpg'):
unprocessed = True
break
if unprocessed:
exportComicDir = exportDirName + "/" + dirname(dirpath).split('/')[-1]
if not os.path.exists(exportComicDir):
os.makedirs(exportComicDir)
exportfile = exportComicDir + "/" + dirpath.split("/")[-2] + " (" + dirpath.split("/")[-1] + ').cbz'
# if not exists(exportfile):
print('*** Create a zip archive of only jpg files form a directory ***')
zipFilesInDir(dirpath, exportfile, lambda name : 'jpg' in name)
"""
dirName = '/Volumes/home/Drive/Comics/Tachiyomi/'
fileslist = list()
for (dirpath, dirnames, filenames) in os.walk(dirName):
unprocessed = False
fileslist += [os.path.join(dirpath, file) for file in filenames if file.endswith('.cbz') == False]
for filename in filenames:
if filename.endswith('.jpg'):
unprocessed = True
break
if unprocessed:
print('*** Create a zip archive of only jpg files form a directory ***')
zipFilesInDir(dirpath, dirpath + "/" + dirpath.replace(dirName,"").replace("/"," (") + ').cbz', lambda name : 'jpg' in name)
# Iterate over the list of filepaths & remove each file.
for file in fileslist:
try:
print("Delete " + file)
os.remove(file)
except:
print("Error while deleting file : ", file)
"""
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment