执行复杂的嵌套循环?

时间:2018-09-03 14:09:11

标签: python loops

我有一个列表“ shapelist”,其中包含许多要使用的目录。 这个循环有很多功能,在过程中的某个地方,我必须添加另一个循环,以将坐标系分配给某些文件。正确的方法是什么?

#This is the initial loop
for i in shapelist:
    arcpy.FeatureToLine_management([i] ,i.replace('ASTENOT.shp', 'ASTENOT_lines'))
    #many more lines with functions
    #at some point I have to add coordinate system information to exported files 
    #how do I do that in this loop without creating perplexing results?

我想将此代码添加到坐标系统分配中。

#Finds and stores to a list the files that need the coordinate system assignment
rootfolder = r'C:\Users\user\Desktop\etg'
import os 
newlist = []
for path, subdirs, files in os.walk(rootfolder):
    for name in files:
        if name==('centerline.shp'):
            newlist.append(os.path.join(path, name))

newlist现在包含需要分配坐标系的文件

        #follows the loop that does the assignment
        for i in newlist:
    ...     sr = arcpy.SpatialReference(2100)
    ...     arcpy.DefineProjection_management(i, sr)

如何在初始循环中添加所有这些内容?

1 个答案:

答案 0 :(得分:0)

由于没有输入数据和期望的输出就很难测试问题的解决方案,并且我从未使用过ArcGIS,因此我只能推测您想做什么:

import pathlib

# Root directory of where your files resides
rootfolder = pathlib.Path(r'C:\Users\user\Desktop\etg')

# Get all files named 'centerline.shp' in this directory and all its
# sub-directories
newlist = rootfolder.glob('**/centerline.shp')

# Define a SpatialReference (?)
spatial_reference_to_use = arcpy.SpatialReference(2100)

# Assign a defined projection to all the files in newlist (?)
for file_to_assign in newlist:
    arcpy.DefineProjection_management(str(file_to_assign),
                                      spatial_reference_to_use)

# From the input file names (in newlist), define 
# the output file names (?)
newlist_out_features = [current_file.with_name('ASTENOT_lines')
                        for current_file in newlist]

# Change features to lines for all the files in newlist (?)
for (current_shape_file, current_out_features) in zip(newlist,
                                                      newlist_out_features):
    arcpy.FeatureToLine_management([str(current_shape_file)],
                                   str(current_out_features))

这看起来像您想要的吗?如果不是,则必须更好地解释您想做什么。