程序仅打印出列表的最后一行

时间:2014-02-21 17:10:40

标签: python csv

你好我正试图让这个程序打印出在底部的类调用中输入的走廊的列表数据。但它只打印出列表中的最后一行。该程序接收.csv文件并转换为列表。不是一个非常有经验的python程序员。

class csv_get(object): # class to being in the .csv file to the program
     import os
     os.chdir('C:\Users\U2970\Documents\ArcGIS')
     gpsTrack = open('roadlog_intersection_export_02_18_2014_2.csv', 'rb')
     # Figure out position of lat and long in the header
     headerLine = gpsTrack.readline()
     valueList = headerLine.split(",")

class data_set(object): # place columns from .csv file into a python dictionary
    dict = {'DESC' : csv_get.valueList.index("TDD_DESC"),
    'ROUTE_NAME' : csv_get.valueList.index("ROUTE_NAME"),
    'CORRIDOR': csv_get.valueList.index("CORRIDOR"),
    'ROADBED': csv_get.valueList.index("DC_RBD"),
    'BEG_RP': csv_get.valueList.index("BEG_RP"),
    'END_RP': csv_get.valueList.index("END_RP"),
    'DESIGNATION': csv_get.valueList.index("NRLG_SYS_DESC")}

class columns_set(object): # append the dict into a list
    new_list = []
    for line in csv_get.gpsTrack.readlines():
        segmentedLine = line.split(",")
        new_list.append([segmentedLine[data_set.dict['DESC']],\
        '{:>7}'.format(segmentedLine[data_set.dict['ROUTE_NAME']]),\
        '{:>7}'.format(segmentedLine[data_set.dict['CORRIDOR']]),\
        '{:>7}'.format(segmentedLine[data_set.dict['ROADBED']]),\
        '{:>7}'.format(segmentedLine[data_set.dict['BEG_RP']]),\
        '{:>7}'.format(segmentedLine[data_set.dict['END_RP']]),\
        '{:>7}'.format(segmentedLine[data_set.dict['DESIGNATION']])])

class data: 
   def __init__(self,corridor):
       for col in columns_set.new_list: # for each column in the list new_list
            self.desc = col[0] 
            self.route = col[1]  # assigns column names to column numbers
            self.corridor = col[2] 
            self.roadbed = col[3]
            self.beg_rp = col[4] 
            self.end_rp = col[5] 
            self.designation = col[6] 

   def displayData(self): # print data for corridor number entered
       print self.desc,\
            self.route,\
            self.corridor,\
            self.roadbed,\
            self.beg_rp,\
            self.end_rp,\
            self.designation

set1 = data('C000021') # corridor number to be sent into data class
# should print all the corridor data but only prints very last record
set1.displayData() 

1 个答案:

答案 0 :(得分:1)

您只存储当前行的数据,并用每一行覆盖它。像self.desc = col[0]这样的行表示“覆盖self.desc,因此它引用col[0]的值。

我不想这么说,但所有这些代码都存在基本层面的缺陷。除了data之外,您的类实际上是函数。甚至data也有缺陷,因为它从外部引入了硬连线元素。

你真的应该使用包含CSV module的Python来将CSV文件解析为列表列表。它甚至可以为您提供字典列表并处理标题行。