1

I have a process where I use arcpy.FeatureClasstoShapefile() to re-create shapefiles. Unfortunately, arcpy.env.overwriteOutput = True does NOT overwrite the previous ones. I have tried using arcpy.Delete_management() on the original shapefiles, but sometimes it doesn't work either.

My question is: if I use os.unlink("asdf.shp") will that delete the whole shapefile (including all those subfiles that windows explorer sees) or just the single file with the .shp extension? Also, does it matter? what will happen to the other files if I just delete the .shp file and then try to create a new shapefile that has the same name?

4
  • The operating system is not aware that a shapefile is a collection of files.
    – Paul
    Apr 4 '17 at 16:03
  • Right. So if you use the os to delete the .shp file, will arc have a problem overwriting all the other parts of the .shp file?
    – Craig T
    Apr 4 '17 at 16:35
  • Does this answer your question? stackoverflow.com/q/303200/2954547 Apr 4 '17 at 20:44
  • No, I want to remove and replace some of the shapefiles in a folder, not the whole folder.
    – Craig T
    Apr 5 '17 at 13:23
3

To delete all components of a shapefile using os.unlink you will need to create a loop that references all of the component files. glob allows you to use the ? and * wildcards for identifying all files with a common name:

import os, glob
for i in glob.glob('asdf.*'):
    os.unlink(i)

A list comprehension will also work:

import os, glob
[os.unlink(i) for i in glob.glob('asdf.*')]

Take caution with your wildcard string that it doesn't include unintended files.

4
  • 1
    ESRI have a list of possible extensions if you want to do an explicit loop: webhelp.esri.com/arcgiSDEsktop/9.2/…
    – Spacedman
    Apr 4 '17 at 17:40
  • I haven't tested it yet, but I'm 95% sure this is the right answer. The glob module is super confusing to me, I've read the python documentation of it and I get that it is all about pattern matching, but am still a bit confused about it. Know of any good resources that explain it a bit better?
    – Craig T
    Apr 4 '17 at 17:59
  • Use a ? to represent any single character, or a * to represent zero or more characters. Unless you're trying to delete more than one shapefile at a time, asdf.* should be sufficient.
    – Bjorn
    Apr 4 '17 at 18:30
  • Unless you're positive that there are no other files in your directory with the same basename, please iterate over the known extensions. Would not be good to accidentally delete counties.shp and counties.docx.
    – Paul
    Apr 5 '17 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.