cjanraf
cjanraf

Reputation: 29

Zip Multiple files with multiple result in Python

Good Day!.

I would like to ask how can you convert a list of ".xlsx(excel)" file from specific folder location to ".zip" files. Example: Path:= C:\My_Program\zip_files

Inside my zip_file folder i have multiple ".xlsx" files. Test1.xlsx Test2.xlsx Test3.xlsx

and i want the output to be in same folder but zip individually. Output: Test1.zip Test2.zip Test3.zip

Hope somebady can help me i am new to python2 or python3.

Upvotes: 0

Views: 2830

Answers (1)

furas
furas

Reputation: 143098

You have standard module zipfile to create ZIP, and glob.glob() or os.listdir() or os.walk() to get filenames in folder.


EDIT: should works (I works for me on Linux)

import os
import zipfile

folder = 'C:\\My_Program\\zip_files'

for filename in os.listdir(folder):
    if filename.endswith('.xlsx'):

        name_without_extension = filename[:-5] # string `.xlsx` has 5 chars

        xlsx_path = os.path.join(folder, filename)
        zip_path =  os.path.join(folder, name_without_extension + '.zip')

        zip_file = zipfile.ZipFile(zip_path, 'w')

        # use `filename` (without folder name) as name inside archive
        # and it will not create folders inside archive
        zip_file.write(xlsx_path, filename)

        zip_file.close()

EDIT: the same with glob

import os
import glob
import zipfile

folder = 'C:\\My_Program\\zip_files'

for file_path in glob.glob(folder+'\\*.xlsx'):

    filename = os.path.basename(file_path)
    print(filename)

    name_without_extension = filename[:-5]
    print(name_without_extension)

    xlsx_path = os.path.join(folder, filename)
    zip_path =  os.path.join(folder, name_without_extension + '.zip')

    zip_file = zipfile.ZipFile(zip_path, 'w')

    # use `filename` (without folder name) as name inside archive
    # and it will not create folders inside archive
    zip_file.write(xlsx_path, filename)

    zip_file.close()

Upvotes: 3

Related Questions