How to compress files using python limiting file size by 50 Mb

Asked

Viewed 949 times

-2

Good afternoon!

I need help creating a python code that reads a folder containing images, check the number of existing images and compress the images in packages of up to 50mb.

  • 1

    ok. What have you done? As the question stands, it looks more like a software order.

  • The most common image formats are already compressed, what you could do is apply some optimization lossy or Lossless depending on what you need. But as the friend mentioned, what you have already tried?

1 answer

0

The script below will accomplish the task of compressing the files into multiple volumes. Just run in the directory where your files are. As the fernandosavio has already said, I suggest you optimize the images for an effective reduction in disk space.

import glob
import zipfile
import os

def compress(filename, volumeSize, filetype='*'):
    ''' Compacta arquivos do diretório em volumes filename{n}.zip
        com o tamanho máximo de volumeSize bytes.

        Uso: compress('volume.zip', 50000000, filetype='jpg')

        filename - Nome dos volumes .zip que serão gerados.
                   Ex: filename='myzip.zip'
                   myzip.zip, myzip1.zip, myzip2.zip, myzip(n)...

        filetype - Se informado compacta apenas os arquivos com a
                   extensão informada. Por padrão compacta todos
                   arquivos do diretório.
                   Ex: filetype='png'

        volumeSize - Tamanho máximo em bytes dos volumes .zip.
                     Ex(50MB): volumSize = 50000000

    '''
    userFileName = filename

    if filetype != '*':
        filesToCompress = [file for file in glob.glob('*.' + filetype)]
    else:
        filesToCompress = [file for file in glob.glob('*.png')]

    volumNumber = 1
    for file in filesToCompress:
        if os.path.isfile(filename):
            tmp = open(filename, 'rb').read()

        with zipfile.ZipFile(filename, 'a') as myzip:
            myzip.write(file)

        zipVolumeSize = os.stat(filename).st_size
        # se com a inclusão do arquivo exceder o tamamho maximo do volume
        if zipVolumeSize > volumeSize:
            # recupera o arquivo antes da inclusão
            with open(filename, 'wb') as myzip:
                myzip.write(tmp)

            # cria um novo volume zip e insere o arquivo
            name, extension = userFileName.split('.')
            filename = name + str(volumNumber) + '.' + extension
            with zipfile.ZipFile(filename, 'a') as myzip:
                myzip.write(file)
            volumNumber += 1
    print('{} arquivos compactados em {} volumes.'.format(len(filesToCompress),
                                                              volumNumber))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.