mercredi 7 novembre 2018

Getting info from next line in for loop

I am using a for loop to read a file of coordinates line by line. In some cases I need the information from the next line in order do math at the current line, such as the distance formula.

The file contents look like this:

X66.745 Y108.729 
X67.255 Y108.584 
X139.519 Y90.769
X142.494 Y90.161
X143.062 Y90.068

It has other content in it, however this is the what the useful content looks like.

My current code is:

def get_xy_coord(line):
    x_coord = []
    y_coord = []
    line_list = line.split()
    x_ = line_list[1].split('X')
    x_ = x_[1]
    x_coord.append(x_)
    y_ = line_list[2].split('Y')
    y_ = y_[1]
    y_coord.append(y_)
    return x_coord[-1:], y_coord[-1:]




### Load File

file_name = 'path'  # put your filename here

with open(file_name, 'r+') as f:
    contents = f.readlines()

    for line in contents:
        if 'X' in line:
            x1, y1 get_xy_coord(line)
            #get x2 , y2 to do distance formula

I have read other post on getting the next line, but none of them have worked for my application, such as the next() option, which I think is because I am working with a file rather than a list of values. After using the content of line and the line after it, I would still like to just advance 1 line as if it where a normal for loop iteration.

Aucun commentaire:

Enregistrer un commentaire