24.04.2019 г.

Python script to extract multiple rar file's

# TODO: Add check if file exists if try to extract and if true delete them before extract!

# Import some module's
import os
import sys
# Require to install patool module
import patoolib
import multiprocessing as mp

# Hard code param if not add from termonal
if len(sys.argv) > 1:
    assert os.path.exists(sys.argv[1])
    PATH_TO_FILE = sys.argv[1]
else:
    PATH_TO_FILE = r"D:\Movies\Man.with.a.Plan.S01.HDTV.x264-Scene"


def extract_function(line):
    dir = os.path.dirname(line)
    # This function use for extract file, need to use multiprocessing
    try:
        patoolib.extract_archive(line, outdir=dir)
    except:
        raise "Some error acquire when try to extract {line}".format(line=line)
    else:
        print("{line} was successfully extract!".format(line=line))


class MainCLass:

    def __init__(self, path_to_search, param):
        self.search_param = param
        self._path_to_Search = path_to_search

    def search_to_path(self):
        """
        Method used for search zip files in folder
        :return: List with file conteins rar
        """
        list_with_files = []
        for root, dirname, filename in os.walk(self._path_to_Search):
            for file in filename:
                if file.endswith(self.search_param):
                    list_with_files.append(os.path.join(root, file))
        return list_with_files

    def show_file_from_list(self):
        """
        Method use for conteins result of file with suffix rar and yield result
        :return:
        """
        list_with_file = self.search_to_path()
        for line in list_with_file:
            yield line

    def unrar_file_from_list(self):
        my_file = list(i for i in self.show_file_from_list())
        with mp.Pool() as pool:
            result = pool.map(extract_function, my_file)
            return result

    def delete_rar_archive(self):
        # Delete rar arhive! do after unrar them
        for line in self.show_file_from_list():
            os.unlink(line)


if __name__ == '__main__':
    zip_file = MainCLass(PATH_TO_FILE, 'rar')
    # uncoment to unrar file's
    zip_file.unrar_file_from_list()
    # uncoment to delte rar file's
    # zip_file.delete_rar_archive()

Няма коментари :

Публикуване на коментар