trev915
trev915

Reputation: 401

Need help reading coordinates (x,y on different lines) from a file (Python 3.4)

I currently have an assignment I need to do. I am slightly stuck.

How can I read from a file (coordinates.txt), for example with this in it:

500
500
100
100

and somehow get out of that two coordinates, (500,500) and (100,100)?

I know how to do it if each coordinate was on one line, but that's against the specifications, sadly.

I also know how to open and read files, I'm just not sure how to assign 'x' to line 1, 'y' to line 2, 'x' to line 3, etc etc.

The reason for this is to be able to plot the points with the turtle module.

Upvotes: 0

Views: 447

Answers (5)

flamenco
flamenco

Reputation: 2840

Case A:
If your file is test.txt:
500, 500, 100, 100

you can use the following:

with open("test.txt", "r") as f:
  for line in f:
        x, y, z, w = tuple(map(int,(x for x in line.split(" "))))
        t1 = (x, y)
        t2 = (z, w)
        print t1, t2

It prints out:

(500, 500) (100, 100)

You can put all the above into a function and return t1, t2 as your tuples.

Case B:
If test.txt is:

500
500
100
100

Use:

with open("test.txt", "r") as f:
    x, y, z, w = tuple(map(int, (f.read().split(" "))))
    t1 = (x, y)
    t2 = (z, w) 
    print t1, t2

Prints the same result:

(500, 500) (100, 100)

Upvotes: 0

prithajnath
prithajnath

Reputation: 2115

Here is a very straightforward implementation of what you asked which you can use as a reference. I have collected the coordinates as tuples in a list.

 afile = open('file.txt','r')

 count = 0


 alist = []
 blist = []
 for line in afile:

      count = count + 1
      blist.append(line.rstrip()) 
      if count == 2:
           count = 0
           alist.append(tuple(blist))
           blist = []
 print alist

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113915

import itertools

with open(infilepath) as infile:  # open the file

    # use itertools.repeat to duplicate the file handle
    # use zip to get the pairs of consecutive lines from the file
    # use enumerate to get the index of each pair
    # offset the indexing of enumerate by 1 (as python starts indexing at 0)

    for i, (x,y) in enumerate(zip(*itertools.repeat(infile, 2)), 1):
        print("The {}th point is at x={}, y={}".format(i, x, y))

Upvotes: 1

mhawke
mhawke

Reputation: 87064

You can use iter() to create 2 iterators, and then zip these together to combine 2 lines into a tuple:

with open('coordinates.txt') as f:
    for x, y in zip(iter(f), iter(f)):
        print('({}, {})'.format(int(x), int(y))
        t.setpos(int(x), int(y))
        t.pendown()
        t.dot(10)
    # etc....

Upvotes: 0

user3835277
user3835277

Reputation:

You should be using with to safely open and close the file you're reading from.

Here's some code:

coords = list()
coord  = (None, None)
with open('file.txt', 'r') as f:
    for indx, line in enumerate(f):
        if indx % 2 == 0:
            coord[0] = int(line.strip())
        else:
            coord[1] = int(line.strip())
            coords.append(coord)

Open the file and read each line. On every even line (if the index is divisible by 2), store the number as the first element of a tuple. On every other line, store the number as the second element of the same tuple, and then append the tuple to a list.

You can print the list like this:

for c in coords:
    print(c)

Upvotes: 1

Related Questions