Zipping file with shutil module

2.6k views Asked by At

I use below code to moving files to their specific folders but at the end I don't know how i can zip those folders. Note: i want use shutil module to zip the file.

import shutil
import os
source="/tmp/"
destination1="/tmp/music/"
destination2="/tmp/picture/"
destination3="/tmp/video/"

if not os.path.exists(destination1):
    os.makedirs(destination1)
if not os.path.exists(destination2):
    os.makedirs(destination2)
if not os.path.exists(destination3):
os.makedirs(destination3)

for f in os.listdir(source):
    if f.endswith(".MP3") or f.endswith(".wma") or f.endswith(".WMA") or f.endswith(".mp3") :
        shutil.move(source + f,destination1)
    if f.endswith(".png") or f.endswith(".PNG") or f.endswith(".jpg") or f.endswith(".JPG") or f.endswith(".GIF") or f.endswith(".gif"):
        shutil.move(source + f,destination2)
    if f.endswith(".MP4") or f.endswith(".mp4") or f.endswith(".WMV") or f.endswith(".FLV") or f.endswith(".flv") or f.endswith(".wmv"):
        shutil.move(source + f,destination3)

#now zipping:

shutil.make_archive("archive",'zip',"/tmp/","music"+"video"+"picture") 
1

There are 1 answers

3
Marcin Fabrykowski On
"music"+"video"+"picture"

gives you

'musicvideopicture'

the simplest way will be make dir /tmp/archive/ and there music, video, pictures, and then

shutil.make_archive("archive",'zip',"/tmp/archive")

Edit: consider using gztar :)

Edit2:

import shutil
import os
source = "/tmp/"
dest_base = "/tmp/archive/"
destination1 = dest_base + "music/"
destination2 = dest_base + "picture/"
destination3 = dest_base + "video/"

audio_ext = ('mp3', 'wma')
pictu_ext = ('png', 'jpg', 'gif')
video_ext = ('mp4', 'wmv', 'flv', 'avi')

if not os.path.exists(destination1):
    os.makedirs(destination1)
if not os.path.exists(destination2):
    os.makedirs(destination2)
if not os.path.exists(destination3):
    os.makedirs(destination3)

for f in os.listdir(source):
    ext = f.split('.')[-1].lower()
    if ext in audio_ext:
        shutil.move(source + f, destination1)
    elif ext in pictu_ext:
        shutil.move(source + f, destination2)
    elif ext in video_ext:
        shutil.move(source + f, destination3)

#now zipping:
shutil.make_archive("archive", 'gztar', "/tmp/archive")