我在使用 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 - 压缩文件有额外不需要的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16818131/