-2

I have a file with a list of tuples like that:

(1, 4)

(230, 45), etc.

I want read the first line and take the values (x, y), and read them in my function of the program.

For example: (1, 4) # is the line 1 (x, y)

put them in the function ... #values (x, y) run them

then read the line 2 (x, y) of my file put them in the function ....#values (x, y) run it... and stop when the lenght of the file is done.

MY CODE is:

# opens file, reads contents, and splits it by newline
with open('listprueba.log', 'r') as f:
     data = f.read().split('\n')
     for i in range(len(data)):
         int_list= [int(i) for i in data()]
         x= (int (i[0]))
         y=(int (i[1]))
         print 

and the function of the program is:

log.verbose()
env = environ()
class MyLoop(loopmodel):

 # This routine picks the values to be refined 
            def select_loop_atoms(self):
#  insertion of values x, y
                return selection(self.residue_range(x, y))

What can I change in my CODE, to run it?

Hdez
  • 151
  • 7
  • possible duplicate of [How to read numbers from file in Python?](http://stackoverflow.com/questions/6583573/how-to-read-numbers-from-file-in-python) – aruisdante Feb 17 '15 at 21:08

1 Answers1

0

Check out the ast module: https://docs.python.org/2/library/ast.html

The literal_eval function will create a tuple from each line. The line in the file should just be (1, 2) Then you can loop over the tuples and do what you need to do with x and y.

import ast

with open('temp.txt', 'r') as f:
     lst = [ast.literal_eval(line) for line in f.readlines()]

for t in lst:
    x, y = t
    # do what you need to do
robert_x44
  • 9,224
  • 1
  • 32
  • 37
  • But, The file has the list of tuples (1, 4) is the line 1, (230, 45) is the line 2, etc. I read the values (x, y) for example of the line 1 and then use it in my function of program...when the program end, return to line 2, take the values (230, 45) and run the function again...and stop when the length of my file is done. What can I do it, can you give me some spoor plis= – Hdez Feb 18 '15 at 15:46
  • In the place marked # do what you need to do, just call your function(x, y). Have you tried that? – robert_x44 Feb 18 '15 at 16:14
  • yes, I tried with x=lst[0], and just print the first line, now I'm searching how return to line 2. Thanks – Hdez Feb 18 '15 at 16:24
  • You don't need x=lst[0]. Inside that for loop, x and y are set to the values of the NEXT line in your file. So the first time through your loop, x=1 and y=4, the next time through the loop, x=230 and y=45. All you need to do inside that loop is call your function with x and y. Exactly like fx(x, y). Don't mess with lst[0], it will always be the tuple (1, 4). – robert_x44 Feb 18 '15 at 16:33