0

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.

cjanraf
  • 21
  • 3
  • You should list any actions you have attempted so far, stack overflow is not a code writing service. – Thomas Smyth - Treliant Dec 01 '17 at 07:27
  • show your code and error message. – furas Dec 01 '17 at 08:14
  • import zipfile import os working_folder = 'C:\\My_Program\\zip_files\\' files = os.listdir(working_folder) files_py = [] – cjanraf Dec 02 '17 at 14:07
  • for f in files: with zipfile.ZipFile(str(f) + '.zip', 'w') as myzip: if f.endswith('.xlsx'): ff = os.path.join(working_folder, f) files_py.append(ff) for f1 in files: myzip.write(f1) for a in files_py: ZipFile.write(os.path.basename(a), compress_type=zipfile.ZIP_DEFLATED) – cjanraf Dec 02 '17 at 14:07
  • put code in question. There will be more readable. – furas Dec 02 '17 at 14:16

1 Answers1

3

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()
furas
  • 134,197
  • 12
  • 106
  • 148