3

newbie python query.

Using python 2.7.3

Trying the following code:

#Read in from a file
BNG = csv.reader(open('BNG.csv', 'rU'), delimiter = ',')
BNG.next()

#Get the output file ready
outputFile = open('BNGandLatLon.csv', 'wb')
output=csv.writer(outputFile,delimiter=',')
output.writerow(['Lat', 'Lon', 'E', 'N'])

#Loop through the data 
for E,N in BNG:
    lat, lon = OSGB36toWGS84(float(E), float(N)) 
    output.writerow([str(lat), str(lon), str(E), str(N)])
#Close the output file
outputFile.close()

But it falls over at the iteration over BNG with:

ValueError: too many values to unpack

I've checked out this error (eg Iterate over a string 2 (or n) characters at a time in Python) and think it's to do with for E, N in BNG: finding one item (E and N) instead of two separate E and N values. But I'm having real problems coding this up from the BNG.csv file. Have used .item, zip and izip but haven't been able to get it right. Some help would be v welcome. Cheers

Community
  • 1
  • 1
mark
  • 537
  • 6
  • 25
  • Can you check your `BNG.csv` file for any lines that have more than one comma? The error is suggesting that at some point the CSV module gives more than two values for a row, which generates the exception when it tries to unpack them into the `E, N` variables. – Blckknght Sep 21 '13 at 22:19
  • 1
    For testing, it might also be productive to replace your current `for` statement with `for line in BNG: try: E,N = line; except ValueError: print(line)` (with newlines and indentation as appropriate), followed by the rest of the body of the loop. – Blckknght Sep 21 '13 at 22:23
  • That error indicates that you have *more* than 2 items, not fewer. – Ignacio Vazquez-Abrams Sep 21 '13 at 22:56
  • I was calling python from R and the .csv R was writing for python to read did indeed have three values. Many thanks for tips. Lessons learned. – mark Sep 22 '13 at 07:43

1 Answers1

0

As the error suggests, at some point in the file there is a line that does not have two elements. An easy way to find that line:

i = 0
for E, N in BNG:
    print i
    i += 1
    lat, lon = ...
    output.writerow(...)

When the script errors out, it will have printed the last successful line -- so check the next line in the file.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237