I have written a program (with some help) that extracts data from a csv and creates a kml for viewing in Google Earth. It works fine... I have now tried to amend it to work with different data and I keep getting this error-
我编写了一个程序(有一些帮助),从csv中提取数据,并创建一个kml,用于在谷歌地球上查看。它工作正常…我现在试着修改它以处理不同的数据,我一直得到这个错误。
TypeError: __new__() takes exactly 7 arguments (2 given)
I can't work out what it means, as I have changed very little of the original program, just the namedtuple part, the all_locations = (location_info(*line[0:5]) for line in csv_reader)
(to reflect that there are only 6 namedtuple entries) and have amended the 'ExtendedData' part of the KML.
我无法计算出它的含义,因为我对原始程序的修改非常少,只有namedtuple部分,all_location = (location_info(*line[0:5])在csv_reader中排队)(以反映只有6个namedtuple条目),并修改了KML的“ExtendedData”部分。
I'm scratching my head here... Any ideas?
我在挠头……什么好主意吗?
from Tkinter import *
from tkFileDialog import askopenfilename
import Tkconstants
from collections import namedtuple
import csv
import os
master = Tk()
master.title("KML creation")
path = ""
counter = 0
def counter_label(label):
def count():
global counter
counter += 1
label.config(text="Loading: " + str(counter))
label.after(1000, count)
count()
def getPath():
options = {}
options['defaultextension'] = '.csv'
#options['filetypes'] = ('Comma Separated Values', '*.csv') #only windows
options['initialdir'] = 'C:\\Python27'
options['initialfile'] = 'myfile.csv'
options['title'] = 'Choose File for KML creation...'
Tk().withdraw()
path = askopenfilename(**options)
counter_label(l)
print(path)
location_info = namedtuple('location_info', 'NAME, DATE, TIME, LAT, LON, DESCRIPTION')
input_filename = path
output_filename = "mapppp.kml"
with open(input_filename, 'r') as input_file:
csv_reader = csv.reader(input_file, delimiter=';')
print next(csv_reader) # gets rid of the header line
all_locations = (location_info(*line[0:5]) for line in csv_reader) # the slicing is due to the trailing ;
with open(output_filename, 'w') as output_file:
write_header(output_file)
for location in all_locations:
output_file.write(get_kml(location))
write_footer(output_file)
for files in os.listdir("."):
if files.endswith(".csv"):
print files
print ("File Created. ")
output_file.close()
input_file.close()
def write_header(output_file):
output_file.write(
"""<?xml version='1.0' encoding='UTF-8'?>\n
<kml xmlns='http://www.opengis.net/kml/2.2'>\n
<Folder>\n
<name> </name>\n""")
def get_kml(location_info):
return"""
<Folder>
<ScreenOverlay>
<name>Absolute Positioning: Top left</name>
<Icon>
<href>http://a2.twimg.com/profile_images/1345561985/_sq_normal.png</href>
</Icon>
<overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/>
<screenXY x="0" y="1" xunits="fraction" yunits="fraction"/>
<rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
<size x="0" y="0" xunits="fraction" yunits="fraction"/>
</ScreenOverlay>
<name> {CID} </name>
<Placemark>
<Style id="sn_16">
<LabelStyle>
<color>ff0000ff</color>
<colorMode>normal</colorMode>
<scale>1</scale>
</LabelStyle>
<IconStyle>
<Icon>
<href>http://www.sytech-consultants.com/images/GE%20KML/Circle/4.png</href>
<scale>1.0</scale>
</Icon>
</IconStyle>
</Style>
<name> {REF} ({DESCRIPTION}) </name>
<ExtendedData>
<Data name='Ref'>
<value>
{NAME}
</value>
<Data name='Date'>
<value>
{DATE}
</value>
</Data>
<Data name='Time'>
<value>
{TIME}
</value>
</Data>
</ExtendedData>
<Point>
<altitudeMode>relativeToGround</altitudeMode>
<extrude> 1 </extrude>
<coordinates>{LON},{LAT}, 25 </coordinates>
</Point>
</Placemark>
</Folder>""".format(**location_info._asdict())
def write_footer(output_file):
output_file.write(
"""
</Folder>
</kml>""")
button_opt = {'fill': Tkconstants.BOTH, 'padx': 25, 'pady': 25}
b = Button(master, text="Choose a file for KML creation", command=getPath)
l = Label(master)
l.pack()
b.pack(**button_opt)
master.mainloop()
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Users\zackj\Desktop\ZacksKMLCreator.py", line 45, in getPath
for location in all_locations:
File "C:\Users\zackj\Desktop\ZacksKMLCreator.py", line 41, in <genexpr>
all_locations = (location_info(*line[0:7]) for line in csv_reader) # the slicing is due to the trailing ;
TypeError: __new__() takes exactly 7 arguments (2 given)
1 个解决方案
#1
1
You are attempting to create a location_info
namedtuple object from a CSV row that contains only two columns.
您试图从只包含两列的CSV行创建location_info namedtuple对象。
Python slices allow you to slice beyond the length of a sequence; line[0:5]
on a line that only contains 2 values returns a new list of just two values. This is an error in your CSV file; you need to verify that every row has enough columns.
Python切片允许您切出序列的长度;在一行只包含两个值的行中,返回两个值的新列表。这是CSV文件中的一个错误;您需要验证每一行都有足够的列。
Note that line[:5]
would have the same result, and that slices 5 elements of each CSV result row (not 6, the stop value is not included); you are also slicing the row, not the CSV file (you seem to be under the impression that slicing line
will result only 6 namedtuple objects).
注意,行[:5]会得到相同的结果,并且每个CSV结果行的5个元素(不是6,停止值不包括在内);您还在切割行,而不是CSV文件(您似乎在这样的印象中,切割线只会导致6个namedtuple对象)。
In any case, you probably want to use csv.DictReader()
instead to go straight to dictionaries for your template formatting. The csv.DictReader
tool has the additional
在任何情况下,您可能都希望使用csv.DictReader(),而不是直接使用字典来进行模板格式化。csv。口述记录工具有附加功能。
location_info = namedtuple('location_info', 'NAME, DATE, TIME, LAT, LON, DESCRIPTION')
input_filename = path
output_filename = "mapppp.kml"
with open(input_filename, 'r') as input_file:
csv_reader = csv.reader(input_file, delimiter=';')
#1
1
You are attempting to create a location_info
namedtuple object from a CSV row that contains only two columns.
您试图从只包含两列的CSV行创建location_info namedtuple对象。
Python slices allow you to slice beyond the length of a sequence; line[0:5]
on a line that only contains 2 values returns a new list of just two values. This is an error in your CSV file; you need to verify that every row has enough columns.
Python切片允许您切出序列的长度;在一行只包含两个值的行中,返回两个值的新列表。这是CSV文件中的一个错误;您需要验证每一行都有足够的列。
Note that line[:5]
would have the same result, and that slices 5 elements of each CSV result row (not 6, the stop value is not included); you are also slicing the row, not the CSV file (you seem to be under the impression that slicing line
will result only 6 namedtuple objects).
注意,行[:5]会得到相同的结果,并且每个CSV结果行的5个元素(不是6,停止值不包括在内);您还在切割行,而不是CSV文件(您似乎在这样的印象中,切割线只会导致6个namedtuple对象)。
In any case, you probably want to use csv.DictReader()
instead to go straight to dictionaries for your template formatting. The csv.DictReader
tool has the additional
在任何情况下,您可能都希望使用csv.DictReader(),而不是直接使用字典来进行模板格式化。csv。口述记录工具有附加功能。
location_info = namedtuple('location_info', 'NAME, DATE, TIME, LAT, LON, DESCRIPTION')
input_filename = path
output_filename = "mapppp.kml"
with open(input_filename, 'r') as input_file:
csv_reader = csv.reader(input_file, delimiter=';')