Paul Vio
Paul Vio

Reputation: 57

Split lines's strings from a txt file in 2 different arrays

I have a text file with x and y coordinates. I am trying to store the coordinates to x and y arrays. This is the file I want to store.

100 511
52 502
384 94
46 506
54 508
399 101
394 93

I expect to be like this

x[0] = 100, y[0] = 511;
x[1] = 52, y[1] =502

and so on

for n in range(0,lines[0].find(' ')):
    i = 0
    x[i] = x[i] + n
    i = i + 1

I have tried something like this to find the 'space' but it didn't work. Does anyone have an idea?

Upvotes: 0

Views: 63

Answers (3)

Narendra Kamatham
Narendra Kamatham

Reputation: 340

Try this

num_list = [line.strip('\n').split() for line in open('numbers.txt').readlines()]
x, y = zip(*num_list)
print x, y

Result: ('100', '52', '384', '46', '54', '399', '394') ('511', '502', '94', '506', '508', '101', '93')

Read number.txt and zip it.

Upvotes: 0

Yujin Kim
Yujin Kim

Reputation: 139

Raw answer:

x = []
y = []

with open(file_path) as f:
    for line in f:
        x_coord, y_coord = line.split()
        x.append(x_coord)
        y.append(y_coord)

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71570

Try using:

x, y = zip(*[i.split() for i in lines])

Upvotes: 4

Related Questions