циклически перемещаясь по папкам, создавая пространственный индекс - PullRequest
1 голос
/ 18 августа 2011

Я создал скрипт для создания пространственного индекса всех растров, и он работал нормально при запуске в одном каталоге, но когда я попытался изменить его для запуска в подкаталогах как часть os.walk, он начал давать много ошибок , Можете ли вы, ребята, помочь с текущей, которую я просто не могу исправить.

Спасибо

Python 2.6.5 (r265: 79096, 19 марта 2010 г., 21:48:26) [MSC v.1500 32 bit (Intel)] Введите «помощь», «авторское право», «кредиты» или «лицензия» для более информация.

[оценить RasterExtent_toSHP_Ver2.py] Чтение файлов из P: \ 2011 \ Job_154_PythonScript_for_AOI \ Working \ Orthophotomosaic Changing Справочник по: P: \ 2011 \ Job_154_PythonScript_for_AOI \ Working \ фотомонтаж из снимков, обработанных на ортофотоскопе \ 1 Обработка 2 .tif файлов в каталоге. [ '308000_8105000.tif', '309000_8105000.tif'] 308000_8105000.tif Создано: P: \ 2011 \ Job_154_PythonScript_for_AOI \ Working \ фотомонтаж из снимков, обработанных на ортофотоскопе \ 1 \ Temp_Polygon_Extent_1.shp Заполнение: 308000_8105000 TIFF P: \ 2011 \ Job_154_PythonScript_for_AOI \ Working \ фотомонтаж из снимков, обработанных на ортофотоскопе \ 1 64000000 309000_8105000.tif Создано: P: \ 2011 \ Job_154_PythonScript_for_AOI \ Working \ фотомонтаж из снимков, обработанных на ортофотоскопе \ 1 \ Temp_Polygon_Extent_2.shp Заполнение: 309000_8105000 TIFF P: \ 2011 \ Job_154_PythonScript_for_AOI \ Working \ фотомонтаж из снимков, обработанных на ортофотоскопе \ 1 64000000 [] Слияние: [] в: Spatial_Extent.shp arcgisscripting.ExecuteError: Не удалось выполнить. Параметры не действительный. ОШИБКА 000735: Входные наборы данных: Требуется значение ПРЕДУПРЕЖДЕНИЕ 000725: Выходной набор данных: набор данных P: \ 2011 \ Job_154_PythonScript_for_AOI \ Рабочая \ фотомонтаж из снимков, обработанных на ортофотоскопе \ 1 \ Spatial_Extent.shp уже существует. Не удалось выполнить (объединить).

# Creates a shape file containing the extent of all the files of RasterType in the current directory and subdirectories.
# Options to only process files which have projection
# Option to move and rename files which don't have a projection
# Outputs extent to a shape file with a defined projection

#IMPORTANT - delete "NoProj" directory

import arcpy, glob, os, sys
from arcpy import env, mapping
path = os.getcwd()
env.workspace = path
env.overwriteOutput = True
os.chdir(path)
origPath = path

# IMPORTANT Options to SET
RasterType = ['tif', 'jpg', 'ecw'] # add/remove Raster extensions as required
RootDirectory = path
CheckProjection = 1 # '1' to check if files projected and '0' not to. With 0 will create extent of all RasterFiles in dirctory
RenameFiles = 0 # '1' to rename and move unprojected files projected and '0' not to.
geometry_type = "POLYGON"
ProjectionTemplate = r"C:\Python26\GDA_1994_MGA_Zone_55_Project.shp"
ProjectionRef = r"C:\Python26\GDA_1994_MGA_Zone_55_Project.prj"
has_m = "DISABLED"
has_z = "DISABLED"
#spatial_reference = arcpy.SpatialReference(ProjectionTemplate)
spatial_reference = arcpy.SpatialReference("C:\\Python26\\GDA_1994_MGA_Zone_55_Project.prj")
f = open(origPath+'\\NoProjection.txt', 'a')
f.write("Log of files without projection"+"\n")
f.close()

#FileList =[]
print 'Reading files from ' + path

if RenameFiles == 1:
    os.mkdir(origPath+'\\NoProj') # creates directory to place non-projected files in. Delete if it exists

# Misc counts
x=0
z=x+1
NoProjCount=0
ProjCount=0
for root, dirs, files in os.walk(RootDirectory+'\\'):
    for directory in dirs:
        currentPath=root+directory
        os.chdir(currentPath)
        print "Changing Directory to: " + os.getcwd()
        for Raster in RasterType:
            FileList = glob.glob("*." + Raster)
            FileCount = len(FileList)
            print "Processing " + str(FileCount) + " ." + str(Raster) + " files in the directory."
            print FileList
            for File in FileList:
                desc = arcpy.Describe(File)
                SR = desc.spatialReference
                PositionDot = File.find('.')
                FileNm = File[0:PositionDot]
                RasterObj = arcpy.Raster(File)
                if CheckProjection == 1:
                    if SR.name == "Unknown":
                        print "Projection of " + str(File) + " is " + SR.name + " so skipping and logging status."
                        f = open(origPath+'\\NoProjection.txt', 'a')
                        f.write(str(File)+"\n")
                        f.close()
                        if RenameFiles == 1: 
                            PositionDot = File.find('.')
                            ext =File[PositionDot:]
                            Name = File[0:PositionDot] # Character string to retain from xth character to yth character
                            newName=Name+ext
                            print Name+ext+" renamed as " + newName
                            os.rename(File,"NoProj\\"+newName)
                        else:
                            NoProjCount=NoProjCount+1
                    else:    
                        print File
                        ProjCount=ProjCount+1
                        RasterFile = arcpy.Raster(File)
                        RasterExtent = RasterFile.extent
                        FileFmt = RasterObj.format
                        FileSz=RasterObj.uncompressedSize
                        XMAX = RasterExtent.XMax
                        XMIN = RasterExtent.XMin
                        YMAX = RasterExtent.YMax
                        YMIN = RasterExtent.YMin
                        pnt1 = arcpy.Point(XMIN, YMIN)
                        pnt2 = arcpy.Point(XMIN, YMAX)
                        pnt3 = arcpy.Point(XMAX, YMAX)
                        pnt4 = arcpy.Point(XMAX, YMIN)
                        array = arcpy.Array()
                        array.add(pnt1)
                        array.add(pnt2)
                        array.add(pnt3)
                        array.add(pnt4)
                        array.add(pnt1)
                        polygon = arcpy.Polygon(array)

                        arcpy.CreateFeatureclass_management(currentPath,"\Temp_Polygon_Extent" + "_" + str(z), geometry_type, ProjectionTemplate, has_m, has_z, spatial_reference)
                        ShapeFile = currentPath+"\Temp_Polygon_Extent" + "_" + str(z) + ".shp"
                        arcpy.CopyFeatures_management(polygon, ShapeFile)             
                        print "Created: " + ShapeFile

                        arcpy.AddField_management(ShapeFile,'FileName','TEXT')
                        arcpy.AddField_management(ShapeFile,'FileFormat','TEXT')
                        arcpy.AddField_management(ShapeFile,'FileSource','TEXT')
                        arcpy.AddField_management(ShapeFile,'FileSize','INTEGER')
                        desc = arcpy.Describe(ShapeFile)
                        rows = arcpy.UpdateCursor(ShapeFile)

                        print 'Filling in: ', str(FileNm), str(FileFmt), str(currentPath), int(FileSz)
                        #rows.insertRow(row)
                        for row in rows:
                            row.FileName = str(FileNm)
                            row.FileFormat = str(FileFmt)
                            row.FileSource = str(currentPath)
                            row.FileSize = int(FileSz)
                            rows.updateRow(row)
                        x=x+1
                        z=z+1
                #cleaning up
                if x>1:
                    SpatialExtent='Spatial_Extent.shp'
                    #try:
                    #    os.remove(currentPath+"\\"+SpatialExtent)
                    #except:
                    #    print SpatialExtent +" Created and continuing."
                    arcpy.CreateFeatureclass_management(currentPath, SpatialExtent, geometry_type, ProjectionTemplate, has_m, has_z, spatial_reference)
                    list =[]
                    lstFCs = arcpy.ListFeatureClasses(currentPath+"\Temp_Polygon_Extent*")
                    print lstFCs
                    for fc in lstFCs:
                        print fc
                        list.append(fc)
                    print 'Merging: ' + str(list) + 'to: '+ SpatialExtent
                    arcpy.Merge_management(list, currentPath+'\\'+SpatialExtent)
                    #print 'Deleting identical entries and temp files'
                    #arcpy.DeleteIdentical_management("Extent.shp", ["SHAPE"])
                    #arcpy.Project_management("Extent.shp", "Extent_prj.shp", ProjectionRef)
                    arcpy.DefineProjection_management(currentPath+'\\'+SpatialExtent, ProjectionRef)
                    print 'Created and Projected '+ currentPath+'\\'+SpatialExtent+" to " + ProjectionRef +', deleting Temp files and exiting'
                    print 'PROCESSED ' +str(z-1) + ' files of which ' + str(NoProjCount) + ' were not projected'
                    for item in list:
                        arcpy.Delete_management(item)
                    #del row, rows
                    x=0
                    z=0
...