質問

I recently wrote a python script to select certain files within a directory and save them to a new archive within that directory. The script works with the exception that it creates a duplicate archive within the new archive. I think it has something to do with the arcname I used and the loop but I'm really not sure. As I'm sure is obvious by looking at my code I am a beginner so I am sure there is plenty of room for improvement here. Any ideas as to where the problem is? Also if you have any suggestions for improving the code I'm all ears.

    import os,arcpy,zipfile

inputfc = arcpy.GetParameterAsText(0) # User Inputs Feature Class Path 

desc = arcpy.Describe(inputfc)

fcname = desc.basename

zname =  fcname + ".zip"

gpath = os.path.dirname(inputfc)

zpath = os.path.join(gpath,zname)

zfile = zipfile.ZipFile(zpath, "w")

for f in os.listdir(gpath):
    fpath = os.path.join(gpath, f)
    if f.startswith(fcname):
        zfile.write(fpath,f,compress_type = zipfile.ZIP_DEFLATED)


zfile.close()

these are the files within the new archive

Edit: After aruisdante answered my question I decided to just change the zname variable to

zname = "zip" + fcname + ".zip" #ugly but it worked thanks

役に立ちましたか?

解決

This:

zfile = zipfile.ZipFile(zpath, "w")

Creates a new Zip file at zpath

for f in os.listdir(gpath):

Iterates through all of the files at gpath. Since gpath is also the root of zpath, then the zip file you just created will be one of the files in gpath. So it gets included in the archive. You will need to exclude it:

for f in (filename for filename in os.listdir(gpath) if filename != zname):
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top