File compression

Before I ask for help with this, I need to know if this will actually compress the files. (for example text files.)

# Function : file_compress
def file_compress(inp_file_names, out_zip_file):

# function : file_compress
# args : inp_file_names : list of filenames to be zipped
# out_zip_file : output zip file
# return : none
# assumption : Input file paths and this code is in same directory.

# Select the compression mode ZIP_DEFLATED for compression
# or zipfile.ZIP_STORED to just store the file
 compression = zipfile.ZIP_DEFLATED
print(f" *** Input File name passed for zipping - {inp_file_names}")

# create the zip file first parameter path/name, second mode
print(f' *** out_zip_file is - {out_zip_file}')
zf = zipfile.ZipFile(out_zip_file, mode="w")

 for file_to_write in inp_file_names:
# Add file to the zip file
# first parameter file to zip, second filename in zip
  print(f' *** Processing file {file_to_write}')
zf.write(file_to_write, file_to_write, compress_type=compression)

except FileNotFoundError as e:
print(f' *** Exception occurred during zip process - {e}')
# Don't forget to close the file!

Why do you hate us so much, that you want us to read code with one
space indents?

I do NOT hate anyone.

That is NOT my code.

Here is revised idiomatic current 3.x code, untested, with indents and the error of passing input filenames twice fixed.

import zipfile

def compress(input_files, zip_file. compression=zipfile.ZIP_DEFLATED):
    """Write in np_file_names compressed to out_zip_file.

    Input file paths and this code must be in the same directory.
    Pass zipfile.ZIP_STORED to just store the files.
    with zipfile.ZipFile(zip_file, mode="w") as zf:
        for file in input_files:
            zf.write(file, compress_type=compression)

AFAIK this will work, but I leave it to you to test.

1 Like

Thanks I will test it.

If it’s not your code, how did it get into your post? Why are you asking questions about it? Where did it come from?

Whether you typed it yourself, letter by letter, or copied and pasted it in one great big chunk, you put it into your message to us, and requested help about it, which requires us to read it. That makes it effectively yours.

Single space indents are legal to the interpreter, but horrible to read for humans.

Obviously I don’t think you actually and literally hate us. The term is hyperbole.

I found an easier way to do file compression.

import math 
import os
import zipfile
import shutil

print ("Compress files in /home/andy/Downloads/")
shutil.make_archive('Compressed_Files', format='zip', root_dir='/home/andy/Downloads/')