Search code examples
pythonjython

make list of CVS file w/o header


this function finds the gives the population of either a specific state or all the states all the states when parameters is left blank. when I leave the parameters blanks though it gives me a error because there are headers in the first 3 rows of the file.

def findpop(state=None):
     f=open(getMediaPath("population_state_reduced (2).csv"),"rt")
     for line in f: 
       parts = line.split(',')
       if state is None:
          return [(parts[4], int(parts[5]))]
       else:
         for line in f:
             if parts[4] == state.capitalize():
                  return int(parts[5])
print findpop()

Solution

  • Just skip the first 3 lines:

    def findpop(state=None):
        f = open(getMediaPath("population_state_reduced (2).csv"), "rt")
        index = 1
        for line in f:
            if index > 3:
                parts = line.split(',')
                if state is None:
                    return [(parts[4], int(parts[5]))]
                else:
                    for line in f:
                        if parts[4] == state.capitalize():
                            return int(parts[5])
            index += 1
    
    print findpop()