2020-6-22 23:03 /
近年来收藏下载了不少单行本或者本子,近期在整理这些收藏。主要先看看封面是否合口味,但是一个个的点开预览比较麻烦。再加上乱七八糟的合集也比较多,有些还有解压密码,压缩包名字还不是书名。为了提高效率写了这个脚本。
脚本的主要功能就是解压出默认的第一张图片,解压出来的图片名称和压缩包一样。
本身没啥技术含量,发出来留给需要的人。

使用前需要安装 Python 和 WinRAR,然后在命令行运行  pip install rarfile  安装依赖。
然后需要根据自己的情况修改  workDir  为自己的电脑里面的单行本目录。修改 rarfile.UNRAR_TOOL 为自己的电脑里面的 unrar.exe 路径,这个在 WinRAR 安装目录下。有解压密码的情况,把 rf.setpassword('pw') 这一行取消注释 ,将 pw 修改为解压密码。
最后在命令行运行 python manga-first.py

代码地址



import rarfile
import os, zipfile, shutil
from os import path
from os.path import join
from pathlib import PureWindowsPath
from fnmatch import fnmatch

# 这里设置漫画的路径
workDir = r"e:\comic\test"

# 设置 unrar.exe 路径
rarfile.UNRAR_TOOL = r"D:\Program Files\WinRAR\UnRAR.exe"

# Set to '\\' to be more compatible with old rarfile
rarfile.PATH_SEP = '\\'


files = [f for f in os.listdir(workDir)]
zipFiles = filter(lambda name : fnmatch(name, "*.zip"), files)
rarFiles = filter(lambda name : fnmatch(name, "*.rar"), files)


def moveFile(basePath, filename, rarName):
    shutil.move(join(basePath, filename), join(basePath, path.splitext(rarName)[0] + path.splitext(filename)[1]))


def writeFile(outputPath, originFile):
    with open(outputPath, 'wb') as outputFile:
        shutil.copyfileobj(originFile, outputFile)

def extractFirstFile(basePath, rarName, filetype='rar'):
    compressFile = rarfile.RarFile
    if filetype == 'zip':
        compressFile = zipfile.ZipFile
    file1 = path.join(basePath, rarName)
    with compressFile(file1) as rf:
        # 如果需要设置解压密码在这里设置
        # rf.setpassword('pw')
        lst = rf.namelist()
        idx = 0
        firstFile = lst[idx]
        while not PureWindowsPath(firstFile).suffix and idx < len(lst):
            idx += 1
            firstFile = lst[idx]
        if not PureWindowsPath(firstFile).suffix:
            return
        with rf.open(firstFile, 'r') as originFile:
            writeFile(path.join(basePath, path.splitext(rarName)[0]+path.splitext(firstFile)[1]), originFile)

for f in zipFiles:
    extractFirstFile(workDir, f, 'zip')
for f in rarFiles:
    extractFirstFile(workDir, f, 'rar')

Tags: script tool