Python: How to read a text file containing co-ordinates in row-column format into x-y co-ordinate arrays?
One method:
x,y = [], []
for l in f:
row = l.split()
x.append(row[0])
y.append(row[1])
where f is the file object (from open() for instance)
You could also use the csv library
import csv
with open('filename','r') as f:
reader = csv.reader(f,delimeter=' ')
for row in reader:
x.append(row[0])
y.append(row[1])
And you can also use zip to make it more succinct (though possibly less readable:
x,y = zip(*[l.split() for l in f])
where f is the file object, or
import csv
x,y = zip(*csv.reader(f,delimeter=' '))
again where f is the file object. Not that the last two methods will load the entire file into memory (although if you are using python 3 you can use generator expressions and avoid that).
Read it per lines, and split it using split
:
with open('f.txt') as f:
for line in f:
x, y = line.split()
#do something meaningful with x and y
Or if you don't mind with storing the whole list to your computer's memory:
with open('f.txt') as f:
coordinates = [(c for c in line.split()) for line in f]
And if you want to store the x
s and y
s in separate variables:
xes = []
ys = []
with open('f.txt') as f:
for line in f:
x, y = line.split()
xes.append(x)
ys.append(y)