PAV
PAV

Reputation: 49

Reading (x,y) points from file to list in Python

I am trying to extract points from a file formatted like this

(311.7836  , -399.777),
(-238.3153 , -399.310),
(107.8696  , -398.783),
(188.6595  , -397.295)

and directly pass them to a list of points in my program like so :

pts = [
(311.7836  , -399.777),
(-238.3153 , -399.310),
(107.8696  , -398.783),
(188.6595  , -397.295)
]

So far I have tried :

data = [line.strip() for line in open("myfile.txt", 'r')]

but i am getting :

['(311.7836, -399.777),', '(-238.3153, -399.310),', '(107.8696, -398.783),', '(188.6595, -397.295)']

Also I tried using readline() and strip() and other likewise approaches I found here but to no avail. I am new to python thanks for the help.

Upvotes: 1

Views: 631

Answers (4)

user16337074
user16337074

Reputation:

This happens because you didn't handle the comma that's at the end of each line.

You can rstrip() it in the following way:

data = [line.rstrip(",") for line in open("myfile.txt", 'r')]

However, if you are planning to process those numeric pairs, you should create a list of tuples instead:

data = [eval(line.rstrip(",")) for line in open("myfile.txt", 'r')]

Note: try to avoid eval() as much as possible, I've used it for the sake of simplicity. Splitting the string and float-casting the values would be a better idea.

Upvotes: 1

patate1684
patate1684

Reputation: 649

This should work :

data = [(float(line.strip()[1:].split(',')[0]), float(line.strip()[1:].split(',')[1][:-1])) for line in open("myfile.txt", 'r')]

or if you prefer in multiple line :

data = []
for line in open("myfile.txt", 'r'):
    x = line.strip()[1:].split(',')
    data.append((float(x[0]), float(x[1][:-1])))

Upvotes: 1

Gal Perelman
Gal Perelman

Reputation: 47

df = pd.read_csv(file, header=None).dropna(axis=1)
df = df.apply(lambda x: x.str.strip('()'))

   0            1
0  311.7836     -399.777
1  -238.3153    -399.310
2  107.8696     -398.783
3  188.6595     -397.295

Upvotes: 0

John Coleman
John Coleman

Reputation: 51998

You can use literal_eval from the ast module:

import ast

with open("myfile.txt", 'r') as f:
    lines = f.read().split(',\n')
    data = [ast.literal_eval(line) for line in lines]

print(data)

With you sample data this prints:

[(311.7836, -399.777), (-238.3153, -399.31), (107.8696, -398.783), (188.6595, -397.295)]

Upvotes: 1

Related Questions