我正在尝试重命名一些KML文件 1)空格_ 2) - 到_
我在Arcmap中运行脚本。对于前两个,它运作正常。
但对于(和)它出错了?
# Rename file
path = "C:\\DATA\\"
files = os.listdir(path)
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, file.replace("-", "_")))
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, file.replace(" ", "_")))
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, file.replace("(", "_")))
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, file.replace(")", "_")))
目标是我需要导入KML文件,将它们导入Gdb,然后将它们附加到一个激动层。
整个脚本已经有效了。但我仍然需要手动重命名文件,而gdb不会接收文件 - 减去blancs和(或)签名默认情况下我有很多kml文件。
在整个脚本下工作正常,如果我手动重命名 - 或(或)或空白
# Name: BatchKML_to_GDB.py
# Description: Converts a directory of KMLs and copies the output into a single fGDB.
# A 2 step process: first convert the KML files, and then copy the featureclases
# Import system models
import arcpy, os
# Rename file
path = "C:\\DATA\\"
files = os.listdir(path)
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, file.replace(" ", "_")))
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, file.replace("-", "_")))
# Set workspace (where all the KMLs are)
arcpy.env.workspace= (r"C:\DATA")
# Set local variables and location for the consolidated file geodatabase
outLocation = "C:\\WorkingData\\fGDBs"
MasterGDB = 'AllKMLLayers.gdb'
MasterGDBLocation = os.path.join(outLocation, MasterGDB)
# Create the master FileGeodatabase
arcpy.CreateFileGDB_management(outLocation, MasterGDB)
# Convert all KMZ and KML files found in the current workspace
for kml in arcpy.ListFiles('*.kml'):
print "CONVERTING: " + os.path.join(arcpy.env.workspace,kml)
arcpy.KMLToLayer_conversion(kml, outLocation)
# Change the workspace to fGDB location
arcpy.env.workspace = outLocation
# Loop through all the FileGeodatabases within the workspace
wks = arcpy.ListWorkspaces('*', 'FileGDB')
# Skip the Master GDB
wks.remove(MasterGDBLocation)
for fgdb in wks:
# Change the workspace to the current FileGeodatabase
arcpy.env.workspace = fgdb
# For every Featureclass inside, copy it to the Master and use the name from the original fGDB
featureClasses = arcpy.ListFeatureClasses('*', '', 'Placemarks')
for fc in featureClasses:
print "COPYING: " + fc + " FROM: " + fgdb
fcCopy = fgdb + os.sep + 'Placemarks' + os.sep + fc
arcpy.FeatureClassToFeatureClass_conversion(fcCopy, MasterGDBLocation, fgdb[fgdb.rfind(os.sep)+1:-4])
# Clean up
del kml, wks, fc, featureClasses, fgdb
答案 0 :(得分:1)
显然为什么这不起作用 - 一旦你的一个循环实际上重命名了一个文件,后续的循环将无法找到它,因为它们仍在寻找原始名称!
您需要一个SINGLE循环,将所有.replace()
个操作链接在一起,以便将文件直接重命名为其最终名称。