Python' TypeError:__ new __()需要7个参数(给定2个)'

时间:2013-07-29 10:34:50

标签: python arguments typeerror

我编写了一个程序(有一些帮助),它从csv中提取数据并创建一个kml,以便在Google Earth中查看。它工作正常......我现在尝试修改它以使用不同的数据,我不断收到此错误 -

TypeError: __new__() takes exactly 7 arguments (2 given)

我无法理解其含义,因为我对原始程序的改动很少,只改变了命名元素部分all_locations = (location_info(*line[0:5]) for line in csv_reader)(以反映只有6个命名元组条目)并修改了'ExtendedData'是KML的一部分。

我在这里挠头......有什么想法吗?

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 个答案:

答案 0 :(得分:1)

您正在尝试从仅包含两个列的CSV行创建location_info namedtuple对象。

Python切片允许您切片超出序列的长度;仅包含2个值的行上的line[0:5]将返回仅包含两个值的新列表。这是CSV文件中的错误;您需要验证每个行是否有足够的列。

请注意,line[:5]具有相同的结果,并且每个CSV结果行的片段 5 元素(不是6,不包括停止值);你也在切片,而不是CSV文件(你似乎认为切片line只会产生6个namedtuple对象)。

在任何情况下,您可能希望使用csv.DictReader()直接到字典中进行模板格式化。 csv.DictReader工具有额外的

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=';')