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?
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With