0

I have a file where each line has a pair of coordinates like so:

[-74.0104294, 40.6996416]

The code that I'm using to read them in is:

with open('Manhattan_Coords.txt', 'r') as f:
    mVerts = f.read().splitlines()

This reads in all 78 lines into a list, but it reads them in as strings, so when I print them out it shows up as:

['[(-74.0104294, 40.6996416]', ... , '[-74.0104294, 40.6996416]']

(Imagine the ... as 76 more coordinates like the first and last)

How can I read in each of these coordinate pairs as a list so that I am left with a list of 78 sublists with 2 floats inside each sublist?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
jqwerty
  • 37
  • 1
  • 6
  • Is it a typo that you have `'[(-74.0104294, 40.6996416]'`? ie, the extra opening parentheses? – dawg Sep 07 '14 at 22:46

2 Answers2

1

For each line, you need to:

  1. Read it
    ... using a for loop to iterate over the file
  2. Strip whitespace including newlines
    ... using str.strip()
  3. Lose the first and last characters (brackets)
    ... using string slicing: [1:-1]
  4. Split on the substring ', '
    ... using str.split() and a list comprehension.
  5. Convert the resulting strings into floats
    ... using float()
  6. Add each pair of floats to a list
    ... using list.append()

That looks like this:

m_verts = []
with open('Manhattan_Coords.txt') as f:
    for line in f:
        pair = [float(s) for s in line.strip()[1:-1].split(", ")]
        m_verts.append(pair)

After which, m_verts looks like this:

>>> m_verts
[[-74.0104294, 40.6996416], ... ]

In general, you're better off iterating over the lines of a file than reading them all into a list at once with methods like splitlines() ... it's more readable, and with large files much more efficient.

Also, notice that I've used the more pythonic under_score style to name m_verts, rather than your camelCase style - and that there's no need to specify 'r' when opening a file for reading.

Community
  • 1
  • 1
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
0

even better way than @ZeroPiraeus solution use ast.literal_eval which can evaluate any literal of python (here a list literal compound of float literal)

import ast
m_verts = []
with open('Manhattan_Coords.txt') as f:
    for line in f:
        pair = ast.literal_eval(line)
        m_verts.append(pair)

but for construction of the list even better is list comprehension

import ast
with open('Manhattan_Coords.txt') as f:
    m_verts = [ast.literal_eval(line) for line in f]
Xavier Combelle
  • 10,968
  • 5
  • 28
  • 52