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

2つの引数を決定するためのロジック全体をキャプチャしたかどうかzip.writeはわかりませんが(コードからは明らかではありません)、そうでない場合は、簡単に調整できるはずです。

また、最後にそれが必要かどうかはわかりません。ツリー内(それぞれのサブディレクトリ内)で発生する可能性のあるその方法で名前が付けられたすべてのファイルを圧縮するのではなく、その方法で名前が付けられた1つのファイルreturnのみを圧縮する効果があります。そのようなファイルが1つしかないことがわかっている場合は、そのままにしておくこともできます(少しスピードアップします)。複数のファイルがある場合にそのようなファイルがすべて必要な場合は、を削除してください。returnreturn

編集:OPが望んでいる「1つのこと」はファイルではなくディレクトリであることが判明しました。その場合、最も簡単な解決策として、次のことをお勧めします。

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ファイルを作成することは望ましくありません。メンバーが1つだけの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 に答える