Where to incorrporate IF and Else if file doesnt exist after os.walk? Python Question.

2724
4
03-06-2016 04:09 PM
BrianButtaccio
New Contributor

I am extremely new to python so any help would be greatly appreciated. How would you skip the arcpy.Merge and arcpy.Clip if 'AAA010.shp' does not exist in the directory that os.walk is going through. I will have more code after the last line in this snippet. Currently, the script just skips completely over the 'AAA010.shp' even though it exists.

import os, fnmatch, arcpy

arcpy
.env.workspace  =  rC:\Users\sysadmin\desktop\datamanagement\MGCP.gdb

fcMerged
= MergedFeatureClass

fcClipped
= ClippedFeatureClass

fcToClip
= rC:\Users\sysadmin\desktop\datamanagement\Country.shp

filesMatched
= list()

for root, subfolders, files in os.walk(rC:\Users\sysadmin\desktop\datamanagement\MGCP_Raw’):

 
for f in fnmatch.filer(files, AAA010.shp’):
  filesMatched
.append(os.path.join(root,f))

if 'AAA010.shp' in filesMatched:

  arcpy
.Merge_management (filesMatched, fcMerged)

  arcpy
.Clip_analysis (fcMerged, fcToClip, Extraction_Mine)

else: pass

0 Kudos
4 Replies
RebeccaStrauch__GISP
MVP Emeritus

brian, looks like geonet may have hiccup' don you question and duplicated it multiple times.  I would delete this one and a few of the other dupes so you only have one.

that has happened to me before (typically when my connection was flaky for a few minutes)

0 Kudos
VinceAngelo
Esri Esteemed Contributor

You should also mention that this question was asked in gis.stackexchange​ (twice, in fact), but was deemed unclear.  It would probably help if you provide more information, including the version of ArcGIS in use, the contents of the directories, and, after adding a lot more diagnostics, the output of the script with those diagnostics.  It's very difficult to help based on the information provided.

- V

0 Kudos
DanPatterson_Retired
MVP Emeritus

I deleted the multiple entries....thought spammy was back

PS  please format your  code

Code Formatting... the basics++

WesMiller
Regular Contributor III
>>> import os
>>> mypath = r"Some\path"
>>> if os.path.exists(mypath):
  print 'do stuff'

Edit:

Here is a better example:

Consider you have a file structure like below

now if myfile points to the proper directory you would do the following

for root, subfolders, files in os.walk(myfile):
  if os.path.exists(os.path.join(root,'New Text Document1.txt')):
    print 'yes'
0 Kudos