使用shutil modu压缩文件

2024-04-24 04:54:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用下面的代码将文件移动到特定的文件夹,但最后我不知道如何压缩这些文件夹。 注意:我想使用shutil模块压缩文件。在

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") 

Tags: orpathsourcemoveifosexistsnot
1条回答
网友
1楼 · 发布于 2024-04-24 04:54:30
"music"+"video"+"picture"

给你

^{pr2}$

最简单的方法是制作dir/tmp/archive/还有音乐、视频、图片, 然后呢

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

编辑: 考虑使用gztar:)

编辑2:

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")

相关问题 更多 >