6

I want to be able to overwrite a shapefile if it exists. I think my code needs some tweaking. I am using v10. I am able to delete the actual .shp file but the .dbf, .shx, etc still remain, so if I try to overwrite again, I get an error.

How can I remove all the files associated with the shapefile?

DoesItExist = True
geometry_type = "POLYGON"
print "Your shapefile is being generated."
out_path = raw_input("Enter in path to save shape file: ")
out_name = raw_input("Enter in name of shape file: ")
while DoesItExist == True: 
 if (os.path.exists(os.path.join(out_path, out_name))):
 print "This file already exists. Do you wish to overwrite it?"
 choice = raw_input("Y/N:")
 if (choice == 'Y' or choice == 'y'):
 print "File will be over written"
 os.remove(os.path.join(out_path, out_name))
 #arcpy.CreateFeatureclass_management(out_path, out_name, geometry_type)
 DoesItExist = False
 else:
 print "Choose new file name/location!"
 out_path = raw_input("Enter in file path: ")
 out_name = raw_input("Enter in file name: ")
else:
 print "Shapefile created in: " + str(os.path.join(out_path, out_name))
 arcpy.CreateFeatureclass_management(out_path, out_name, geometry_type)
 DoesItExist = False
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Mar 7, 2013 at 0:05
1
  • 3
    You can use arcpy.Delete_management(shapefile) Commented Mar 7, 2013 at 4:09

2 Answers 2

19

You shouldn't have to delete the shapefile. Just add the following lines to your script:

import arcpy
arcpy.env.overwriteOutput = True

That will allow arcpy.CreateFeatureclass_management to overwrite the existing shapefile with all of its associated files (dbf, shx, prj etc.).

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
answered Mar 7, 2013 at 0:23
8

There is also the exists function instead of using os. Remember to import env.

import arcpy
from arcpy import env
env.workspace = "d:/myfolder"
fc = "roads.shp"
#Delete feature class if it exists
if arcpy.Exists(fc):
 arcpy.Delete_management(fc)
answered Mar 7, 2013 at 0:36
3
  • 1
    Thanks awesomo for the reminder to import env. I'll update my answer. Commented Mar 7, 2013 at 0:47
  • oh wow...thanks so much. My error was in forgetting to include/import env. smh@self. Thanks again! Commented Mar 7, 2013 at 15:05
  • There's no need to import env specifically. Just use arcpy.env.workspace = "d:/myfolder" after import arcpy. Commented Jul 16, 2017 at 23:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.