GeoEki
GeoEki

Reputation: 437

coordinates (str) to list

I have a very long txt file containing geographic coordinates..the format for each row looks like this:

501418.209 5314160.484 512.216
501418.215 5314160.471 512.186
501418.188 5314160.513 512.216

so separated by a blank (" ") and at the end a line break (\n)

I need to import that file into a list...so far I only managed to import it as a string and then tried to converted in into a list. Unforunately, I have no idea how I can keep the formatting of the txt file, as I need to perform calculations on each row.

My solution so far to import the txt file to a string variable:

fileobj = file(source,'r')
data = ""
for line in fileobj.readlines():
    linevals = line.strip().split(" ")
    data += "%s %s %s\n" % (linevals[0], linevals[1], linevals[2])
print type(data)

And my solution for importing as list that didn't work:

fileobj = file(source,'r')
data = []
for line in fileobj.readlines():
    linevals = line.strip().split(" ")
    data.append(linevals)

On stackoverflow I found lots of solutions that suggested the eval function - but that didn't work as I need the whole row as one list element. Hope that was clear. Any solutions for this problem? I'm pretty newish to python, but that bothers me for quite some time now. Thank you!

Upvotes: 3

Views: 187

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

You don't need eval or anything other than simply splitting each row and casting to float:

with open(source) as f:
    for row in f:
        print(map(float,row.split()))

[501418.209, 5314160.484, 512.216]
[501418.215, 5314160.471, 512.186]
[501418.188, 5314160.513, 512.216]

If you want all rows in a single list:

with open(source) as f:
    data = [ map(float,row.split()) for row in f] #  python3 ->list(map(float,row.split()))
    print(data)
[[501418.209, 5314160.484, 512.216], [501418.215, 5314160.471, 512.186], [501418.188, 5314160.513, 512.216]]

Or using the csv module:

import  csv
with open(source) as f:
    data = [map(float,row) for row in csv.reader(f,delimiter=" ")]
    print(data)

If you want a flat list of all data:

with open(source) as f:
   data = []
   for row in f:
       data.extend(map(float,row.split())) 

If you are doing a lot of work on the data you may find numpy useful:

import numpy as np

data = np.genfromtxt(source,delimiter=" ").flatten()

Upvotes: 3

Related Questions