PYTHON - Zip each file in directory independently
Question: I've been looking through and have tried a few different codes without
results. What I'm trying to do is zip each file in a subdirectory/folder
independently.

Ex:

> FileName.prj
>
> FileName.dwg
>
> FileName.mp3

Each as it's own .zip

Thanks!


Answer: Try this

    
    
    import os
    import zipfile
    
    folder = "/tmp/in"
    dest_folder = "/tmp/out"
    l = [os.path.join(folder, fname) for fname in os.listdir(folder)]
    os.chdir(folder)
    
    for f in l:
        f_name = f[f.rfind("/")+1:]+".zip"
        z = zipfile.ZipFile(f_name, 'w')
        z.write(f_name[:f_name.rfind(".zip")])
        os.rename(folder+"/"+f_name, dest_folder+"/"+f_name)
    

where folder is you folder that contains files you want to zip and dest_folder
is folder where the zip files will be written.

