Hdez
Hdez

Reputation: 151

How can I iterate tuples in this code python?

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

(1, 4)

(569, 39)

(49, 69)

. . .

I have this CODE, but read it all the lines in the same time, I want read just only line, for example line 1, and have the values x,y for set them in a function, then, return line 2 and take the values x, y, and do it again, and stop when the lenght of my file is done.

What can I change in the code for return the next line?

import ast

def readfile():
     filename = open('file.log')
     result=[]


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

     for t in lst:
          x, y = t
          for t in [(x,y) for x in t[0:] for y in t[:1]]:
               print x, y
               value = (x, y)

               result.append(value)

     return result[1:-1]

print readfile()

Upvotes: 1

Views: 107

Answers (5)

hello_there_andy
hello_there_andy

Reputation: 2083

Here's a solution that buffers your file line-by-line. Buffering saves RAM; useful if the file is huge.

I've adapted your script to:

  1. read line-by-line
  2. print one line ahead (you can remove that functionality if you wish),
  3. removed the need to import ast:

Output

enter image description here

Code

#######################
# define the function #
#######################

def readfile():

    """ Reads a file consisting of a list of tuples (x, y) line-by-line. Prints x and y of the current line and the next line as reading ensues. """

    file_in = open("./tuples.txt","r")  # read the file in, I assume the script is run in the same directory as the tuples list

    result = []

    while True:

        line      = file_in.readline()  # read the file line-by-line
        go_back   = file_in.tell()      # "saves" the current line so we can step back
        next_line = file_in.readline()  # reads the line ahead

        x,y  = str(line).replace("(","").replace(")","").replace(" ","").rstrip().lstrip().split(",")

        # Have we reached the end of the file?
        try: 
            # No...
            x_next, y_next = str(next_line).replace("(","").replace(")","").replace(" ","").rstrip().lstrip().split(",")
            result.append([float(x),float(y)])
            print "current line: "+str(x)+" "+str(y)+" ..next line: "+str(x_next)+" "+str(y_next)

        except ValueError:
            # Yes...
            print "current line: "+str(x)+" "+str(y)+" ..next line: "+"NaN NaN"
            break # break once we read a "next line" that does not exist, i.e. number of lines in file + 1

        line = file_in.seek(go_back) # go back to previous line

    return result

####################
# run the function #
####################

result = readfile()

print "\nresult: "+str(result)

Upvotes: 0

Kevin
Kevin

Reputation: 76194

my end goal is: take the values x, y, of the line 1 and use them in other function, when this function is done, return the line 2 and take other values for do it again, and stop when my lenght of my file is done.

Sounds like you want a function that iteratively yields values from a file. Sample implementation:

import ast

def readfile():
    with open('file.log', 'r') as f:
        for line in f:
            yield ast.literal_eval(line)

def do_something(a,b):
    print "I am doing something with {} and {}".format(a,b)

for x,y in readfile():
    do_something(x,y)

Result:

I am doing something with 1 and 4
I am doing something with 569 and 39
I am doing something with 49 and 69

Upvotes: 1

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

Just replace

    lst = [ast.literal_eval(line) for line in f.readlines()]

 for t in lst:

with

 for t in f.readlines():

Upvotes: 0

diversemix
diversemix

Reputation: 569

Your variable lst is an array so if you want line one you can just return lst[0].

So the trick is to store lst and write a function to return lst[line-1]. Something like this:

def get_at_line(lst, line):
   # do some validation here
   return lst[line-1]

x, y = get_at_line(lst, 1)

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

You are close, but it seems that you got confused. If I understood the question, it would be:

for x, y in lst:
   print x, y

Upvotes: 0

Related Questions