Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to read a text file containing co-ordinates in row-column format into x-y co-ordinate arrays?

I have a text file with numbers stored in the following format:

1.2378 4.5645

6.789 9.01234

123.43434 -121.0212

... and so on.

I wish to read these values into two arrays, one for x co-ordinates and the other for y co-ordinates. Like, so

x[0] = 1.2378

y[0] = 4.5645

x[1] = 6.789

y[1] = 9.01234

... and so on.

How should I go about reading the text file and storing values?

like image 739
AnchalAgrawal Avatar asked Dec 23 '13 01:12

AnchalAgrawal


People also ask

How do you read a column from a text file in Python?

To read a text file in Python, you follow these steps: First, open a text file for reading by using the open() function. Second, read text from the text file using the file read() , readline() , or readlines() method of the file object. Third, close the file using the file close() method.

How do I read a text file line by line in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.


2 Answers

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).

like image 185
Thayne Avatar answered Nov 07 '22 21:11

Thayne


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 xs and ys 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)
like image 33
aIKid Avatar answered Nov 07 '22 22:11

aIKid