How to extract data from a text file and add it to a list?

Viewed 80

Python noob here. I have this text file that has data arranged in particular way, shown below.

x = 2,4,5,8,9,10,12,45
y = 4,2,7,2,8,9,12,15

I want to extract the x values and y values from this and put them into their respective arrays for plotting graphs. I looked into some sources but could not find a particular solution as they all used the "readlines()" method that returns as a list with 2 strings. I can convert the strings to integers but the problem that I face is how do I only extract the numbers and not the rest? I did write some code;


#lists for storing values of x and y
x_values = []
y_values = []

#opening the file and reading the lines
file = open('data.txt', 'r')
lines = file.readlines()

#splitting the first element of the list into parts
x = lines[0].split()

#This is a temporary variable to remove the "," from the string
temp_x = x[2].replace(",","")

#adding the values to the list and converting them to integer. 
for i in temp_x:
     x_value.append(int(i))

This gets the job done but the method I think is too crude. Is there a better way to do this?

3 Answers

You can use read().splitlines() and removeprefix():

with open('data.txt') as file:
    lines = file.read().splitlines()
    x_values = [int(x) for x in lines[0].removeprefix('x = ').split(',')]
    y_values = [int(y) for y in lines[1].removeprefix('y = ').split(',')]

print(x_values)
print(y_values)

# output:
# [2, 4, 5, 8, 9, 10, 12, 45]
# [4, 2, 7, 2, 8, 9, 12, 15]

Since your new to python, here's a tip! : never open a file without closing it, it is common practice to use with to prevent that, as for your solution, you can do this :

with open('data.txt', 'r') as file:
    # extract the lines
    lines = file.readlines()

    # extract the x and y values
    x_values = [
        int(el) for el in lines[0].replace('x = ', '').split(',') if el.isnumeric()
        ]
    y_values = [
        int(el) for el in lines[1].replace('y = ', '').split(',') if el.isnumeric()
        ]

# the final output
print(x_values, y_values)

output:

[2, 4, 5, 8, 9, 10, 12] [4, 2, 7, 2, 8, 9, 12, 15]

Used dictionary to store the data.

# read data from file
with open('data.txt', 'r') as fd:
    lines = fd.readlines()

# store in a (x,y)-dictionary
out = {}
for label, coord in zip(('x', 'y'), lines):
    # casting strings to integers
    out[label] = list(map(int, coord.split(',')[1:])) 

# display data
#
print(out)
#{'x': [4, 5, 8, 9, 10, 12, 45], 'y': [2, 7, 2, 8, 9, 12, 15]}
print(out['y'])
#[2, 7, 2, 8, 9, 12, 15]

In case desired output as list just substitute the main part with

out = []
for coord in lines:
    # casting strings to integers
    out.append(list(map(int, coord.split(',')[1:])))
X, Y = out
Related