【问题标题】:Zipped files have extra unwanted folders压缩文件有多余的不需要的文件夹
【发布时间】:2013-05-24 23:07:56
【问题描述】:

我在使用 zipfile.Zipfile() 函数时遇到了问题。它会正确压缩我的文件,但在输出 zip 文件中会有我不想要的额外文件夹。它确实将所有我想要的文件放在 .zip 中,但它似乎默认添加了正在写入 .zip 文件中的文件的最后几个目录。有没有办法排除这些文件夹?这是我的代码:

import arcpy, os
from os import path as p
import zipfile
arcpy.overwriteOutput = True


def ZipShapes(path, out_path):
    arcpy.env.workspace = path
    shapes = arcpy.ListFeatureClasses()

    # iterate through list of shapefiles
    for shape in shapes:
        name = p.splitext(shape)[0]
        print name
        zip_path = p.join(out_path, name + '.zip')
        zip = zipfile.ZipFile(zip_path, 'w')
        zip.write(p.join(path,shape))
        for f in arcpy.ListFiles('%s*' %name):
            if not f.endswith('.shp'):
                zip.write(p.join(path,f))
        print 'All files written to %s' %zip_path
        zip.close()

if __name__ == '__main__':

    path = r'C:\Shape_test\Census_CedarCo'
    out_path = r'C:\Shape_outputs'

    ZipShapes(path, out_path)

我尝试发布一些图片,但我没有足够的声望点。基本上它在 zip 文件中添加了 2 个额外的文件夹(空)。因此,不要像这样将文件放在 zip 中:

C:\Shape_outputs\Public_Buildings.zip\Public_Buildings.shp

他们是这样出现的:

C:\Shape_outputs\Public_Buildings.zip\Shape_test\Census_CedarCo\Public_Buildings.shp

“Shape_test”和“Census_CedarCo”文件夹是我要复制的 shapefile 的目录,但如果我只是在编写这些文件,为什么还要将子目录复制到 zip 文件中?我想这没什么大不了的,因为我正在压缩文件,但这比什么都烦。

我假设在创建 zip 文件时它只会写入我自己指定的文件。为什么它会在 zip 文件中添加这些额外的目录?有办法解决吗?我在这里错过了什么吗?我很感激任何意见!谢谢

【问题讨论】:

    标签: python python-2.7 zipfile arcpy


    【解决方案1】:

    ZipFile.write(filename[, arcname[, compress_type]]) 中可选的第二个参数是存档文件中使用的名称。您可以从路径的前面删除有问题的文件夹,并将其余部分用作存档路径名称。我不确定 arcpy 究竟是如何为您提供路径的,但应该使用 zip.write(p.join(path,shape), shape) 之类的东西。

    【讨论】:

    • 漂亮!我想知道 arcname 参数是什么......我想我应该多读一点。现在完美运行!再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 2010-12-14
    • 2023-03-19
    相关资源
    最近更新 更多