我创建了一个工作代码,用于将GPX文件转换为ArcGIS中的要素类。不幸的是,我遇到了一个损坏或加密的文件(我真的不知道)。我想为这些文件创建一个例外,因为可能有更多,我不希望这些文件中断长进程。我试图使用python的try创建一个异常,但是现在我得到错误“TypeError:'NoneType'对象不可迭代”第15行是FOR循环。我的代码的简短说明:首先,我设置并为要转换的文件创建名称。然后他们被转换,我已经包括一个计数器,因为我正在转换成千上万的文件。转换后的文件将放入一个列表中,然后在合并中使用该列表在地理数据库中创建一个大的要素类。对于无法转换的文件,我希望代码使用arcpy.AddMessage()为我提供文件名,然后转到其他文件。你有什么想法?这是我的代码:
import arcpy
import datetime
from arcpy import env
arcpy.env.overwriteOutput = True
gpxFolder = 'C:\file\with\GPXs\in\it'
outputGdb = 'C:\the\output\geodatabase'
mergedFile = 'C:the\output\geodatabase\mergedFile'
env.workspace =gpxFolder
def convertGPX2feature(gpxFolder, outputGdb): #, referenceSymbologyLayer, outputLayerFolder
i = 1
fcList = []
for file in arcpy.ListFiles("*.gpx"):
# Convert files from .gpx to feature layer
# First set up the names
inGPX = gpxFolder + "\\" + file
featureName = file.partition(".gpx")[0]
featurename2 = file.partition(".gpx")[1]
fileType = featurename2.split(".")[1]
outfile = outputGdb + "\\" + fileType + "_" + featureName
try:
# Now convert
arcpy.GPXtoFeatures_conversion(inGPX,outfile)
convertedfile = outfile
except:
arcpy.AddMessage("file " + featureName + " failed to convert")
pass
# Add a new field and populate it with the gpx file name to use for the join later
arcpy.AddField_management(convertedfile, "Original_GPX_File", "DOUBLE", 9, "", "", "Original_GPX_File", "NULLABLE", "REQUIRED")
arcpy.CalculateField_management(convertedfile, "Original_GPX_File", featureName)
fcList.append(convertedfile)
# The counter so you know where you are in the iteration
if i%250 == 0:
arcpy.AddMessage(str(i) + " files have been converted at " + str(datetime.datetime.now()))
i += 1
# Merge all of the converted files using fcList as the input
arcpy.AddMessage("And now we merge")
arcpy.Merge_management(fcList, mergedFile )
if __name__ == "__main__":
convertGPX2feature(gpxFolder, outputGdb)
答案 0 :(得分:0)
所以问题是arcpy.ListFiles()突然停止工作。一旦我修复了(不知何故)我遇到了错误,GPX功能已经有了新字段,并且无法使用相同的名称添加另一个,因为转换后的文件对象仍然保存了当损坏的文件存在时最后传递的文件的信息迭代过来。为了解决这个问题,我在try中放了arcpy.AddField()和arcpy.CalculateField()。现在代码工作并传递损坏的文件后给我一个消息,它无法使用arcpy.AddMessage()转换,只合并成功转换的文件。 新的try和except代码如下所示:
outfile = outputGdb + "\\" + fileType + "_" + featureName
try:
# Now convert
arcpy.GPXtoFeatures_conversion(inGPX,outfile)
convertedfile = outfile
# Add a new field and populate it with the gpx file name to use for the join later
arcpy.AddField_management(convertedfile, "Original_GPX_File", "DOUBLE", 9, "", "", "Original_GPX_File", "NULLABLE", "REQUIRED")
arcpy.CalculateField_management(convertedfile, "Original_GPX_File", featureName)
fcList.append(convertedfile)
except:
arcpy.AddMessage("File " + featureName + " could not be converted")
# The counter so you know where you are in the iteration
if i%250 == 0:
arcpy.AddMessage(str(i) + " files have been converted at " + str(datetime.datetime.now()))
i += 1