在Python中为变量分配字段名

时间:2013-06-20 18:15:20

标签: python variables csv

我是Python的新手,我正在尝试检查我正在处理的csv中的空值。我正在使用带有键对值的DictReader对象。我正在使用for循环中的密钥对值来打印出信息(在本例中为kml)。

我去运行该程序,它不喜欢我的变量赋值。这是我收到的错误。

File "./csvtokml3.py", line 31
    Latvariable = str(row["lat_degrees"]),Longvariable = str(row["lon_degrees"])
SyntaxError: can't assign to function call

以下是该计划的代码。

#!/usr/bin/python


#
#
#

import csv

#Input the file name.
fname = raw_input("Enter file name WITHOUT extension: ")

data = csv.DictReader(open(fname + '.csv'), delimiter = ',')

#Open the file to be written.
f = open('csv2kml.kml', 'w')

#Writing the kml file.
f.write("<?xml version='1.0' encoding='UTF-8'?>\n")
f.write("<kml xmlns='http://www.opengis.net/kml/2.'>\n")
f.write("<Document>\n")
f.write("   <name>" + fname + '.kml' +"</name>\n")

for row in data:

    f.write("   <Placemark>\n")
    f.write("       <name>" + str(row["station"]) + "</name>\n")
    ### f.write("       <description>" + str(row[0]) + "</description>\n")
    f.write("       <Point>\n")
    #Check for nulls for lat and long
    Latvariable = str(row["lat_degrees"]),  Longvariable = str(row["lon_degrees"])
    if Latvariable !=null and Longvariable !=null:
        f.write("           <coordinates>" + str(row["lat_degrees"]) + "," + str(row["lon_degrees"]) + "</coordinates>\n")
    f.write("       </Point>\n")
    f.write("   </Placemark>\n")

f.write("</Document>\n")
f.write("</kml>\n")
f.close()

print "File Created. "
print "Press ENTER to exit. "
raw_input()

1 个答案:

答案 0 :(得分:0)

您的语法错误,您想要:

Latvariable, Longvariable = str(row["lat_degrees"]), str(row["lon_degrees"])

而是为多个名称指定多个值。或者,将两个陈述放在不同的行上:

Latvariable = str(row["lat_degrees"])
Longvariable = str(row["lon_degrees"])

你不能像你试过的那样用逗号组合多个赋值语句;它适用于JavaScript但不适用于Python。