How can I read values from a .txt-file and save them into different variables in python and get access to them?

Question:

I’m new learning coding. I’m trying to read a file with several lines. The Lines have x,y coordinate values. The last number z is some random amount of money. I want to save them in different variables in a List.
For example, my .txt-file is like this, only with a few hundred lines more:

0,3,97.72  
0,4,97.69  
0,5,97.66  

and I want this to save line for line, like this:
x = 0 y = 3 z = 97.72

When I then select two random coordinates, I want to get all coordinates between them and plot all the z values with matplotlib. How can I do this?

I tried to save the values with a for loop, but failed.
Edit:
This was my try:

with open(f"example.txt", "r", encoding=ascii) as lines:
    coordinates=[]
    for line in lines:
        x_text,y_text, z_text = line.split(",")
        coordinates.append((int(x_text), int(y_text), float(z_text)))

for x, y  in coordinates:
    if x_text ==x and y_text <= y <=y_text:
        print()
    elif x_text <= x <=x_text and y_text == y:
        print()      
Asked By: gregiroir

||

Answers:

You seem to be able to read the file data into a list of coordinates, so I am assuming that your trouble lies in determining if a given coordinate is inside some sort of bounding box.

Try:

def falls_between(coord, top_left, bottom_right):
    return top_left[0] <= coord[0] <= bottom_right[0] and top_left[1] <= coord[1] <= bottom_right[1]

test_top_left = (0, 0)
test_bottom_right = (4, 4)
coordinates=[]
with open("in.csv", "r") as file_in:
    for row in file_in:
        x, y, z = row.strip("n").split(",")
        coordinates.append([int(x), int(y), float(z)])

for coord in coordinates:
    if falls_between(coord, test_top_left, test_bottom_right):
        print(f"{coord} is inside {test_top_left} and {test_bottom_right}")
    else:
        print(f"{coord} is not inside {test_top_left} and {test_bottom_right}")
Answered By: JonSG
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.