编程语言
首页 > 编程语言> > python-压缩文件有多余的不需要的文件夹

python-压缩文件有多余的不需要的文件夹

作者:互联网

我在使用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文件中添加这些额外的目录?有办法解决吗?我在这里想念什么吗?感谢您的投入!谢谢

解决方法:

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

标签:python-2-7,zipfile,arcpy,python
来源: https://codeday.me/bug/20191123/2066043.html