Skip to content

Instantly share code, notes, and snippets.

@rosco-pc
Created March 11, 2021 12:10
Show Gist options
  • Save rosco-pc/bf1de67307682b7dea91000e8d880cfd to your computer and use it in GitHub Desktop.
Save rosco-pc/bf1de67307682b7dea91000e8d880cfd to your computer and use it in GitHub Desktop.
convert CBR to CBZ
Simple python script to convert CBR to CBZ files
Needed this as some CBR files can not be read by comic book readers on *nix systems
Need to install RarFile (https://rarfile.readthedocs.io/)
Usage: cbr2cbz <cbr file> | <folder>
convert CBR file or all CBR files in a folder to CBZ format
#!/usr/bin/env python
import sys
import os
import shutil
import tempfile
import rarfile
import zipfile
def print_usage():
usage="cbr2cbz A script utility to convert CBR files into CBZ files"
usage+="\n Usage: cbr2cbz <cbr file> | <cbr folder>"
print_err(usage)
#
def extract(filename, directory):
'''
Extract images from a CBR file into a directory
'''
with rarfile.RarFile(filename) as archive:
archive.extractall(path=directory)
def compress (directory, filename):
'''
Compress a folder with images into a CBZ/ZIP file
'''
with zipfile.ZipFile(filename,mode='w',
compression=zipfile.ZIP_DEFLATED) as archive:
for fn in os.listdir(directory):
archive.write('{}/{}'.format(directory,fn),arcname=fn)
def convert(cbr_filename):
'''
Convert CBR file to CBZ, by extracting the RAR archive and
re-compressing to ZIP archive
'''
cbz_filename = '{}.cbz'.format(os.path.splitext(cbr_filename)[0])
temp_dir=tempfile.mkdtemp("cbr2cbz") # create temporary folder
extract(cbr_filename, temp_dir) # Extract images from CBR/RAR into tmp folder
compress(temp_dir, cbz_filename) # Compress images and put them into a CBZ/ZIP
shutil.rmtree(temp_dir) # remove temp fodler
if len(sys.argv)!=2:
print_usage();
sys.exit(-1)
cbr_filename = sys.argv[1]
if os.path.isfile(cbr_filename):
print("Processing "+cbr_filename)
convert(cbr_filename)
elif os.path.isdir(cbr_filename):
for root, dirs, files in os.walk(cbr_filename):
for fn in files:
if fn.endswith('.cbr'):
print("Processing "+fn)
convert(os.path.join(root, fn))
else:
print_usage();
sys.exit(-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment