2013-03-18 25 views
1

我嘗試使用一些代碼在這裏發現多個文件添加到MXD文件MXD: How do I add a shapefile in ArcGIS via python scripting?添加多個形狀文件與ArcPy中

下面的代碼不會返回任何錯誤,但沒有一個shape文件似乎將其添加到空白的mxd文檔中。

任何幫助,爲什麼這是行不通的,將不勝感激。

import arcpy 
import arcpy.mapping 
from shutil import copyfile 
from os import listdir 
from os.path import isfile, join 

def AddAllShapeFilesToNewMXD(source_directory): 
    # Source file is the template that the will be copied to the directory with 
    # All the shape files in it. 
    source_file = 'M:\Ops Field Map\Blank Map.mxd' 

    # Output file is the name of the file that will have the shape files added to it 
    output_file = 'GPS_Map' 
    rev_count = 0 
    while isfile(join(source_directory, output_file + '.mxd')): 
     #Make sure a unique file is created 
     print ('File ' + output_file + '.mxd exists.'), 
     rev_count += 1 
     output_file = output_file + '_rev' + str(rev_count) 
     print ('Trying ' + output_file + '.mxd ...') 

    # Create the destination file. This is the file the shape files are added to 
    destination_file = join(source_directory, output_file + '.mxd') 
    copyfile(source_file, destination_file) 
    print 'MXD file created: ' + destination_file 

    # Get the map doccument 
    mxd = arcpy.mapping.MapDocument(destination_file) 
    # Get the data frame 
    data_frame = arcpy.mapping.ListDataFrames(mxd, "*")[0] 

    # Get a list of all the shape files 
    shp_files = [ f for f in listdir(source_directory) if isfile(join(source_directory, f)) and f.endswith('.shp') ] 

    # Add all the shapefiles to the mxd file 
    for s in shp_files: 
     new_layer_full_path = join(source_directory, s) 
     new_layer = arcpy.mapping.Layer(new_layer_full_path) 
     arcpy.mapping.AddLayer(data_frame, new_layer, "BOTTOM") 
     print 'Layer added ' + new_layer_full_path 
     del new_layer 

    return True 

directory = 'C:\Users\gps\Desktop\dd test' 
AddAllShapeFilesToNewMXD(directory) 
+0

是否顯示打印語句(即「Layer Added」)?如果是的話,你可以發佈該輸出嗎? – garnertb 2013-03-19 01:42:37

回答

0

這是很難知道沒有文件一起玩,但一個原因上面的代碼可以不給了一個錯誤,但不顯示任何內容是,對於許多ArcGIS地圖顯示操作,你必須確保該打開了地理處理>地理處理選項下的「將地理處理操作的結果添加到顯示器」的arcgis地理處理選項。

0

這可能是因爲你缺少這兩個重要的幾行:

arcpy.RefreshActiveView() 
arcpy.RefreshTOC() 
0

看起來你幾乎沒有和這兩個盧卡斯和BelowZero正在提供,如果你的代碼在運行活躍W /好建議會話。如果它創建一個* .mxd供以後使用,我看不到結果保存在哪裏。這裏有一些簡單的示例代碼,請注意最後一行:

mxd = arcpy.mapping.MapDocument(srcdir+'/data_bin/Untitled.mxd') 
data_frame = arcpy.mapping.ListDataFrames(mxd)[0] 
mxd.activeView = data_frame.name 

flowlinesLyr=arcpy.mapping.Layer('..\\NHDPlus\\nhdflowline_en') 
flowlinesLyr.name='NHDPlus Flowlines' 
arcpy.mapping.AddLayer (data_frame, flowlinesLyr,'TOP') 

gagesEventLyr=arcpy.mapping.Layer('..\\NHDPlus\\StreamGageEvent') 
gagesEventLyr.name='Original stream gage locations' 
arcpy.mapping.AddLayer (data_frame, gagesEventLyr,'TOP') 

mxd.saveACopy(datadir+'\NHDPlus'+Region+'_Gage_QAQC.mxd')