Select to view content in your preferred language

Iterating feature classes and writting in a text file

5919
21
Jump to solution
05-30-2015 02:10 AM
KONPETROV
Frequent Contributor

Hi i am trying to export some values from a number of shapefiles to a text file so as to use it to creat a point shapefile. The process is succeded ONLY when i put my files in the table of context. Why is that? **I have only folders no GDBase or .mxd**

In addition there is A problem with my code cause i can't get the right calculation of AVGDISTANCES i put it outside if and for, but nothing changed. FOR EXAMPLE for DISTANCE = 170, 170, 160, 150 i should get AVGDISTANCES= 162.5 not 150.  This is my code:

 import arcpy
    import os
    from arcpy import env
    Routesworkspace = arcpy.GetParameterAsText(2)
    env.workspace = Routesworkspace
    cases = ['RCs4s3s2c10_S', 'RCs4s3s2c20_S', 'RCs4s3s2c30_S', 'RCs4s3s2c40_S']
    for fc in arcpy.ListFeatureClasses():
        for case in cases:
            if fc.startswith(case):
                fields = ['DISTANCE', 'DURATION']
                SUMDISTANCE = 0
                C = 0
                with arcpy.da.SearchCursor(fc, fields, "FID = 0") as cursor:
                    for row in cursor:
                        DISTANCE = row[0]
                        DURATION = row[1]
                        SUMDISTANCE = SUMDISTANCE + DISTANCE
                        C = C + 1 
                        AVGDISTANCE = SUMDISTANCE / C
    outFile.write('' + str(AVGDISTANCE) + '\n')

Is this the right format for a point txt?

Point
0 34.5 23.2 12
1 65.7 56.5 67
2 34.9 97.9 43
3 67.2 34.3 20
0 Kudos
1 Solution

Accepted Solutions
RichardFairhurst
MVP Honored Contributor

After reading your code again I see that currently it is not using embedded cursors like I thought it was (although you edited the code at some point and I may have seen embedded cursors in a previous version of the code).  You probably can still benefit from the Cursor and Dictionary approach, since most likely once you get this working you probably intend to process many more records and use many more SQL statements than your current code shows.  In any case, if your full code actually includes embedded cursors, you should remove the embedded cursors and use the principles my Blog outlined.

In any case, your looping structure appears to reset the distance summation and record counter variables (SUMDISTANCE and C) for each feature class,  Since you only write after processing the entire loop, the variables will have been reset so that only the record(s) of the last feature class will be in the average.  I don't think that is what you want to do (but I still don't know what this code is supposed to average).

If you mean to aggregate and average records across multiple feature classes then the summation and counter variable should be outside the loops.  Alternatively, the write operation perhaps should be inside the loops if multiple averages are actually supposed to be written.  Because you set a filter on the SearchCursor to only read FID=0, which should only be one record, probably only one record from the last feature class is being included in the average.  So that explains why only the last value in your list is being reported, which I believe is what you showed in one post that you added and then deleted at some point.  You need to add that post back, since none of the other posts you have in this thread actually show the numbers you think your are averaging and the result you are getting.

Since you keep editing the code and example data I am commenting on my posts won't make sense to most people reading this thread, since the things I am commenting on disappear and I lose track of what I was seeing.  To avoid that confusion, please add new versions of your code and examples in new posts rather than editing posts we have already commented on until your problem is found and resolved.

Your code should probably look like the code below if you only intend to write one AVGDISTANCE value at the end of the loops (the fields list never changes, so that line has been removed from the loop to avoid processing it repeatedly).

    SUMDISTANCE = 0  
    C = 0  
    fields = ['DISTANCE', 'DURATION'
    cases = ['RCs4s3s2c10_S', 'RCs4s3s2c20_S', 'RCs4s3s2c30_S', 'RCs4s3s2c40_S']  
    for fc in arcpy.ListFeatureClasses():  
        for case in cases:  
            if fc.startswith(case):  
                with arcpy.da.SearchCursor(fc, fields, "FID = 0") as cursor:  
                    for row in cursor:  
                        DISTANCE = row[0
                        DURATION = row[1
                        SUMDISTANCE += DISTANCE  
                        C += 1   
    AVGDISTANCE = SUMDISTANCE / C  
    outFile.write('' + str(AVGDISTANCE) + '\n')

I assume the code you have posted was edited from a longer script or includes code you intend to extend, since although the Duration field is stored in a variable, its value is overwritten in each loop and the values are never actually used.

View solution in original post

21 Replies
JeffWard
Honored Contributor

Are there any errors when you run the code?  And how are you executing the code, are you running it as a standalone script or in the python window of ArcMap?

You will probably need to post your code for the community to really be able to help you - and follow these intructions so it is formatted correctly.

Jeff Ward
Summit County, Utah
KONPETROV
Frequent Contributor

these files are exported from modelbuilder

0 Kudos
SepheFox
Deactivated User

If you don't have an mxd, how can you have a Table of Contents?

KONPETROV
Frequent Contributor

from modelbuilder but then i am using a script as a tool

0 Kudos
DanPatterson_Retired
MVP Emeritus

​then my comment about requiring layers (ie in a project in a table of contents) rather than data on disk

KONPETROV
Frequent Contributor

i ll try it and post my results now

0 Kudos
DanPatterson_Retired
MVP Emeritus

Your script might require a featurelayer and is not using a featureclass or shapefile.  It probably needs the full path to disk

KONPETROV
Frequent Contributor

but all the othres scripts i have used as tools in modelbuilder works fine, only with that, that exports a txt i have problem. Is propably that the cause?

0 Kudos
DanPatterson_Retired
MVP Emeritus

script? not shown...how connected to model...too many possibilities

Why not convert the model to a script and put it in a toolbox.  Modelbuilder is nice for some stuff, but it is easier if you have scripting experience to skip it after you get your workflow going then put it into a script.

I posted a few topics on this "You are not allowed to use Geoprocessing Results... ": The Students get smarter  and "You are not allowed to use Modelbuilder": When Instructors need to get smarter  there are pdf files therein  The Results window options is great because you get a copy of what works