I need to write a script that loops through shapefiles in a folder and adds fields to each shp. It works for one file at a time, but the added for loop go through the folder is throwing an error that I have included after the code. The print statement prints the name of the first file in the folder, then the next line (fieldsShp02 = arcpy.ListFields(file)) throws the error, which says it does not exist.

Why is it making that complaint?

>>> import arcpy
... import arcgisscripting
... import os
... import sys
... import types
... import locale
... #Input FC
... sourceFC = r"G:\Backup.gdb\muni_provided_utilities_points_copy"
... rootdir = r"G:\Orland Park\CH EAST ORLAND^WESTORLAND2"
... fieldsShp01 = arcpy.ListFields(sourceFC)
... newFields = []

... for file in os.listdir(rootdir):
... #Output shp
...     if file.endswith(".shp"):
...         print "The file does exist:", file 
...         fieldsShp02 = arcpy.ListFields(file)
...         for field01 in fieldsShp01:
...             exists = False
...             for field02 in fieldsShp02:
...                 if (field01.name == field02.name and field01.type == field02.type and field01.length == field02.length):
...                     exists = True
...                 if (exists == False):
...                     if (field01.name != 'OBJECTID' and field01.name != 'SHAPE' and field01.name != 'CHECKED'):
...                         newFields.append([field01.name, field01.type, field01.length]) 
...             exists = True         
... for field in newFields:
...     fieldnames = field[0]
...     trimmed_fnames = fieldnames[0:10]
...     arcpy.AddField_management(file, trimmed_fnames, field[1], "", "", field[2], "", "NON_NULLABLE","NON_REQUIRED","")

The file does exist: AbandinedSanitarySewerForceMain.shp

Runtime error Traceback (most recent call last): File "", line 17, in File "j:\apps\arcgis\desktop10.4\arcpy\arcpy__init__.py", line 1138, in ListFields return gp.listFields(dataset, wild_card, field_type) File "j:\apps\arcgis\desktop10.4\arcpy\arcpy\geoprocessing_base.py", line 346, in listFields self._gp.ListFields(*gp_fixargs(args, True)))

IOError: "AbandinedSanitarySewerForceMain.shp" does not exist

1 Answer 1


ArcPy does not know which directory your shapefile is in. You need to provide the full path to the shapefile.

fieldsShp02 = arcpy.ListFields (os.path.join (rootdir, file))

  • I believe if you set the workspace to rootdir, ListFields will work without this.
    – SMiller
    Commented May 22, 2019 at 18:46
  • @Regulus great. Please mark the answer as correct. Commented May 22, 2019 at 19:13

Your Answer

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

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