简体   繁体   中英

Reading text file line by line in Python and storing into struct as coordinates for graphing

I have a text file ordered like this:

A,1,1

B,1,5

C,3,7

D,5,5

E,5,1

The letter being a node label, the first number being an x coordinate, and the second number being ay coordinate.

I'm trying to store these "nodes" as pieces of different arrays (ie letter labels are stored into one array in an element position, x coordinates are stored into an array in a matching element position, and y coordinates are stored into a matching element position)

So for my first node I would have:

A is at position 0 in nodeLabel[]

1 is at position 0 in xCoord[]

1 is at position 0 in yCoord[]

This involves a few concepts from what I understand. First I need to open the file and read from it.

  • The file needs to be read up to a comma or a \\n and store the values

  • Then it needs to switch arrays and read up to the next comma or \\n and store the values.

  • Then it needs to switch arrays and read up to the next comma or \\n and store the values.

  • If the .read function hits a new line then it needs to go to the next line

My problem is that I don't know how to tell Python where I want specific values stored and into which array they should be stored. I found some information on using a split() function. Would this allow me to tell the read() function when to stop?

Right now I have this:

def file_stuff():
with open('Offices.txt') as input_data:
    for line in input_data
        if line.strip() == ',', '\n':
            break
        elif 

I'm not sure what to set my elif condition as either.

Would this make more sense as a struct since I will have to implement a GUI to graph the nodes?

Something like this:

def file_stuff():
    nodes = []
    X = []
    Y = []
    with open('Offices.txt') as input_data:
        for line in input_data:
           n, x, y = line.split(',')
           nodes.append(n)
           X.append(int(x))
           Y.append(int(y))

This is simplistic, as it does not check the validity of the input file, but should do what you wanted if the file is correctly formatted. Another issue is that your function does not return any value, if you want to do further manipulation you should add something like:

   return (n, X, Y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM