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:
For each line, you need to:
for
loop to iterate over the filestr.strip()
[1:-1]
', '
str.split()
and a list comprehension.float()
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.