找到你要的答案

Q:PYTHON - Zip each file in directory independently

Q:Python目录中的每个文件独立拉链

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!

我一直在寻找和尝试了一些不同的代码没有结果。我想做的是zip文件中的每一个独立的子目录/文件夹。

前任:

filename.prj

filename.dwg

filename.mp3

每个都是自己的

谢谢!

answer1: 回答1:

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.

试试这个

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)

哪里是你的文件夹,文件夹中包含要压缩和dest_folder文件文件夹的zip文件将被写入。

python  zipfile