压缩目录目标

时间:2018-07-02 15:05:04

标签: python file-handling python-2.6

我正在Python 2.6中使用此基本脚本来压缩目录:

def zipdir(path, ziph):
    import os, zipfile
    for(dir, _, files) in os.walk(path):
        for file in files:
            ziph.write(os.path.join(dir, file))

ziph = zipfile.ZipFile(name + '.zip', 'w', zipfile.ZIP_DEFLATED)
path = 'c:/test/directory'

问题出在我的新zip文件中。

例如,我要压缩的目标文件夹位于c:/test/directory/myfiles

因此,当我压缩它时,而不是:file.zip/directory/myfiles,

我有:file.zip/test/directory/myfiles

我不想保留“测试”文件夹。

有人可以告诉我如何解决?

2 个答案:

答案 0 :(得分:2)

在python 2.7或更高版本中:

尝试使用“ shutil”软件包

import shutil
import os

zip_path = 'c:/test/new_zip_file'
target_dir_path = 'c:/test/directory'

# such as "c:/test/"
parent_target_dir_path = os.path.dirname(target_dir_path)
# such as "directory"
target_dir_name = os.path.basename(target_dir_path)

shutil.make_archive(zip_path, 'zip', root_dir=parent_target_dir_path, base_dir=target_dir_name)

结果:

new_zip_file.zip
└── directory
    ├── myfile1
    ├── myfile2
    └── myfile3 ...

已编辑

在python 2.6中:

import zipfile

def zipdir(path, ziph):
    import os, zipfile
    parent_dir_name = os.path.basename(path)
    for(dir, _, files) in os.walk(path):
        for file in files:
            path_in_zip = dir[dir.find(parent_dir_name):]
            ziph.write(os.path.join(dir, file) , arcname = path_in_zip+"/"+file)

name = "ziptest"

ziph = zipfile.ZipFile(name + '.zip', 'w', zipfile.ZIP_DEFLATED)
path = 'c:/test/directory'

zipdir(path, ziph)

它使用参数arcname并指定in-zip-path。
例如,ziph.write("c:/test/directory/myfile1" , arcname = "dirctory/myfile1")制作一个诸如ziptest.zip/dirctory/myfile1

之类的zip文件。

答案 1 :(得分:0)

Python 2.7及更高版本:

import shutil

zip_path = 'c:/Desktop/zip_name'  # Note: no '.zip' in the suffix!
root_folder = 'c:/Documents/directory/'
shutil.make_archive(zip_path, 'zip', root_folder)

Python 2.6:

import os
import zipfile

def my_make_archive(zip_path, root_folder):
    zf = zipfile.ZipFile(zip_path, 'w')
    for (folder, sub_folder, filenames) in os.walk(root_folder):
        for filename in filenames:
            abs_file_path = os.path.join(folder, filename)
            rel_file_path = os.path.join(os.path.relpath(folder, root_folder), filename)
            zf.write(abs_file_path, arcname=rel_file_path)
    zf.close()

zip_path = 'c:/Desktop/zip_name.zip'  # Note: has '.zip' in the suffix!
root_folder = 'c:/Documents/directory/'
my_make_archive(zip_path, root_folder)