0

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.

trev915
  • 391
  • 2
  • 11
  • 1
    Exactly how stuck are you - how far have you gotten? Which specific part are you having trouble with? What approaches for it did you try without success? – TigerhawkT3 Oct 21 '15 at 05:16
  • Here is my code so far, I was under the assumption (x,y) coordinates would be on the same line. Since finding out that they're on different lines, i'm completely stumped. here is a screenshot of code: https://gyazo.com/af9bb9a1787e478a1efb23ac61a6fc04 – trev915 Oct 21 '15 at 05:18
  • @trev915 You should really follow Python 3 best practices for this assignment and use `with` to safely open and close the file. –  Oct 21 '15 at 05:24
  • @gragas I 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. – trev915 Oct 21 '15 at 05:26
  • 3
    @trev915 Don't give a screenshot, please paste your code here. And by the way, take a look about [`f.readlines()`](http://www.tutorialspoint.com/python/file_readlines.htm). – Remi Guan Oct 21 '15 at 05:26
  • Here is my code: http://pastebin.com/ehtvfdpX – trev915 Oct 21 '15 at 05:29
  • 2
    @trev915 By "please paste your code here", Kevin means you should post your code on StackOverflow. You can give it nice-looking "code format" be prepending four spaces to each line. –  Oct 21 '15 at 05:32
  • 1
    You only learn when you do your own homework – MohitC Oct 21 '15 at 05:33

5 Answers5

1
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))
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • I think you should tell OP how to use these code, seems like OP doesn't just want to print them. – Remi Guan Oct 21 '15 at 05:31
  • 2
    I couldn't agree more. I'm about midway through an introductory python class currently. I've no clue what these codes are doing, a little explanation would go a long way. I'm trying to learn as well, not just get a quick answer. – trev915 Oct 21 '15 at 05:35
  • Thanks for the edit with the comments, that's a lot more helpful. – trev915 Oct 21 '15 at 06:08
1

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)
0

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....
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • Can you explain a little bit about what "as f" does? Thanks! – trev915 Oct 21 '15 at 05:44
  • @trev915 Check [this question](http://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for). – Remi Guan Oct 21 '15 at 05:49
  • @trev915: `as f` binds the context manager created by the `with` statement to a variable. The context manager ensures that the file will be closed on exit from the context manager. You can do some reading and experimenting to work out how the code in this and other answers works.... in particular you will learn more by experimenting interactively in the Python interpreter. – mhawke Oct 21 '15 at 05:52
0

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)
flamenco
  • 2,702
  • 5
  • 30
  • 46
0

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
prithajnath
  • 2,000
  • 14
  • 17