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.

5
  • You should list any actions you have attempted so far, stack overflow is not a code writing service. Commented Dec 1, 2017 at 7:27
  • show your code and error message. Commented Dec 1, 2017 at 8:14
  • import zipfile import os working_folder = 'C:\\My_Program\\zip_files\\' files = os.listdir(working_folder) files_py = [] Commented Dec 2, 2017 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) Commented Dec 2, 2017 at 14:07
  • put code in question. There will be more readable. Commented Dec 2, 2017 at 14:16

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.