【问题标题】:Zip Multiple Subdirectories With Path To Individual Zips使用单个 Zip 的路径压缩多个子目录
【发布时间】:2013-03-05 22:05:24
【问题描述】:

我需要帮助编辑以下压缩目录内容的脚本。我的最终目标是创建一个脚本,该脚本将查看 C:\Test(其中将有多个目录)并使用 C:\Test 中每个目录的内容创建一个新的 zip 文件。棘手的部分是我需要路径是 C:\ 即使目录的真实路径是 C:\Test。这是可能的还是我在做梦?

谢谢

import zipfile, os

def makeArchive(fileList, archive):

    try:
        a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
        for f in fileList:
            print "archiving file %s" % (f)
            a.write(f)
        a.close()
        return True
    except: return False

def dirEntries(dir_name, subdir, *args):

    fileList = []
    for file in os.listdir(dir_name):
        dirfile = os.path.join(dir_name, file)
        if os.path.isfile(dirfile):
            if not args:
                fileList.append(dirfile)
            else:
                if os.path.splitext(dirfile)[1][1:] in args:
                    fileList.append(dirfile)
        # recursively access file names in subdirectories
        elif os.path.isdir(dirfile) and subdir:
            print "Accessing directory:", dirfile
            fileList.extend(dirEntries(dirfile, subdir, *args))
    return fileList

if __name__ == '__main__':
    folder = r'C:\test'
    zipname = r'C:\test\test.zip'
    makeArchive(dirEntries(folder, True), zipname)

【问题讨论】:

    标签: python zip winzip


    【解决方案1】:

    您可以按如下方式更改存档中文件的路径:

    a.write(PATH_ON_FILESYSTEM, 
            DESIRED_PATH_IN_ARCHIVE
    )
    

    【讨论】:

    • 我似乎无法更改路径,但我稍后会尝试。更重要的是,我需要 scipt 为每个目录创建多个 ZIP 文件。目前,该脚本会制作一个包含每个目录的大型 ZIP。
    猜你喜欢
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多