使用arcGis的用户输入来选择某些csv列

时间:2016-07-30 23:44:56

标签: python csv arcgis

我目前是编码的初学者,也是python编码的新手。

我其实想重写csv文件(读取csv并将其保存到另一个csv

我要问你的是如何从arcGis用户输入中读取某个csv列。

我使用" field"数据类型和"多值"输入,所以我可以选择我想要显示的列。

例如,我有这个csv:

    key, province, population, area
    A1, provA, 100, 20
    B1, provB, 200, 10
    C1, provC, 50, 30

现在从输入中我只选择列的键和区域,我使用:

    GetParameterAsText(0)

然后我使用这段代码:

    headers = arcpy.GetParameterAsText(0)
    newhead = headers.replace("'", "")
    headersList = newhead.split(";")
    arcpy.AddMessage(headersList)

我得到了这个结果( headersList ):

    [u'key', u'area']

当我想从上面的结果中读取某个列时,问题会启动:

    data = []
    with csvdata as csvfile:
        reader = csv.DictReader(csvfile, delimiter=",")
        for row in reader:
            try:
                new_row = [headersList] <--------------- This One
                data.append(new_row)
            except IndexError as e:
                print e
                pass

        with open(csvout, "w+") as to_file:
            writer = csv.writer(to_file, delimiter=",")
            for new_row in data:
            writer.writerow(new_row)

我想让new_row像这样(从 headersList 获取):

    new_row = [row['key'], row['area']]

但我不知道怎么样,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

来自@jedwards的评论,答案是这样的:

data = []
with csvdata as csvfile:
    reader = csv.DictReader(csvfile, delimiter=",")
    for row in reader:
        try:
            new_row = [row[k] for k in headersList]
            data.append(new_row)
        except IndexError as e:
            print e
            pass

    with open(csvout, "wb") as to_file:
        writer = csv.writer(to_file, delimiter=",")
        writer.writerow(headersList)
        for new_row in data:
            writer.writerow(new_row)

再次感谢!