1

下面的 python 代码获取文件列表并将它们压缩。我需要拥有的唯一文件地理数据库(基于文件的数据库)称为“数据”,那么如何修改循环以仅包含名为数据的基于文件的数据库?更具体地说,文件地理数据库存储为系统文件夹,其中包含存储和管理空间数据的二进制文件。所以我需要名为 Data.gdb 的整个系统文件夹。

非常感谢

#**********************************************************************
# Description:
#    Zips the contents of a folder, file geodatabase or ArcInfo workspace
#    containing coverages into a zip file.
# Parameters:
#   0 - Input workspace
#   1 - Output zip file. It is assumed that the caller (such as the
#       script tool) added the .zip extension.
#
#**********************************************************************

# Import modules and create the geoprocessor
import sys, zipfile, arcgisscripting, os, traceback
gp = arcgisscripting.create()

# Function for zipping files 
def zipws(path, zip):
    isdir = os.path.isdir

    # Check the contents of the workspace, if it the current
    # item is a directory, gets its contents and write them to
    # the zip file, otherwise write the current file item to the
    # zip file
    #
    for each in os.listdir(path):
        fullname = path + "/" + each
        if not isdir(fullname):
            # If the workspace is a file geodatabase, avoid writing out lock
            # files as they are unnecessary
            #
            if not each.endswith('.lock'):
                # gp.AddMessage("Adding " + each + " ...")
                # Write out the file and give it a relative archive path
                #
                try: zip.write(fullname, each)
                except IOError: None # Ignore any errors in writing file
        else:
            # Branch for sub-directories
            #
            for eachfile in os.listdir(fullname):
                if not isdir(eachfile):
                    if not each.endswith('.lock'):
                        # gp.AddMessage("Adding " + eachfile + " ...")
                        # Write out the file and give it a relative archive path
                        #
                        try: zip.write(fullname + "/" + eachfile, \
                                       os.path.basename(fullname) + "/" + eachfile)
                        except IOError: None # Ignore any errors in writing file


if __name__ == '__main__':
    try:
        # Get the tool parameter values
        #
        inworkspace = sys.argv[1]
        outfile = sys.argv[2]     

        # Create the zip file for writing compressed data
        #
        zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED)
        zipws(inworkspace, zip)
        zip.close()

        # Set the output derived parameter value for models
        #
        gp.setparameterastext(1, outfile)
        gp.AddMessage("Zip file created successfully")

    except:
        # Return any python specific errors as well as any errors from the geoprocessor
        #
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n    " + \
                str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n"
        gp.AddError(pymsg)

        msgs = "GP ERRORS:\n" + gp.GetMessages(2) + "\n"
        gp.AddError(msgs)
4

2 回答 2

1

遍历目录树的最佳方法是os.walk——为您执行文件/目录分离,并为您执行递归到子目录。

所以:

def zipws(path, zip, filename='Data.gdb'):
  for root, dirs, files in os.walk(path):
    if filename in files:
      zip.write(os.path.join(root, filename),
                os.path.join(os.path.basename(root), filename))
      return

我不确定我是否已经捕获了您想要确定两个参数的整个逻辑zip.write(从您的代码中对我来说并不明显),但如果没有,那应该很容易调整。

另外,我不确定您是否希望return在最后这样做:效果是只压缩一个以这种方式命名的文件,而不是压缩树中可能出现的所有以这种方式命名的文件(在它们各自的子目录中)。如果您知道只有一个这样的文件,不妨留下return(它只会加快速度)。如果您在有多个文件时想要所有此类文件,请删除return.

编辑:原来OP想要的“一件事”是一个目录,而不是一个文件。在这种情况下,我建议作为最简单的解决方案:

def zipws(path, zip, dirname='Data.gdb'):
  for root, dirs, files in os.walk(path):
    if os.path.basename(root) != dirname: continue
    for filename in files:
      zip.write(os.path.join(root, filename),
                os.path.join(dirname, filename))
    return

再次进行类似的猜测,即您想将其用于存档名称的全部谜团

于 2010-08-25T21:18:48.513 回答
0

从这一行开始:

    zipws(inworkspace, zip)

您不想使用此函数从多个文件构建 zip 文件。看来您想构建一个只有一个成员的 zip 文件。

用这个替换它。

     try: 
         zip.write(os.path.join('.', 'Data.gdb'))
     except IOError: 
         pass # Ignore any errors in writing file

扔掉zipws你——显然——不想使用的功能。

阅读这个,它可能会有所帮助:http ://docs.python.org/library/zipfile.html

于 2010-08-25T21:22:24.937 回答