sentientnativeplant
sentientnativeplant

Reputation: 63

I would like to extract x and y values from a txt file

I have some code which stores x and y values into a txt file. The txt file stores the values on each line every time I tell the program to store the data.

It reads like this in the txt file:

[(1.0, 1.80), (2.0, 1.80), (3.0, 0.70), etc...]

I tried to extract the values using the np.genfromtxt() function, but I keep getting the values nan. I read through the documentation but I can't seem to interpret it.

How can I store these x and y values into varibles so that I can further work with them outside of the txt file?

Upvotes: 2

Views: 600

Answers (2)

SpghttCd
SpghttCd

Reputation: 10860

If the structure of all those brackets and white spaces is exactly like you posted:

x = []
y = []
with open('filename.txt') as f:
    for line in f:
        pairs = line[1:-2].split('),')
        for p in pairs:
            x.append(float(p.split(', ')[0].strip()[1:]))
            y.append(float(p.split(', ')[1].strip()))

# print(x, y)
# [1.0, 2.0, 3.0] [1.8, 1.8, 0.7]

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

Use ast module

Ex:

import ast

with open(filename) as infile:         #Read file
    for line in infile:                #Iterate Each line
        print(ast.literal_eval(line))  #Convert to python object

Output:

[(1.0, 1.8), (2.0, 1.8), (3.0, 0.7)]
[(1.0, 1.8), (2.0, 1.8), (3.0, 0.7)]
[(1.0, 1.8), (2.0, 1.8), (3.0, 0.7)]

Upvotes: 3

Related Questions