1

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()
5
  • Is this your actual code? I'd expect result.append() to crash with TypeError: append() takes exactly one argument (0 given). Commented Feb 18, 2015 at 20:53
  • What's your end goal, or are you doing this just to try things out? f.readline() correctly reads one line of the file. Commented Feb 18, 2015 at 20:53
  • @RyanO'Donnell 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. Commented Feb 18, 2015 at 20:59
  • Just skip the lst = and go right to for t in f.readlines(): Commented Feb 18, 2015 at 21:01
  • Loop directly on the file object, that won't read all the lines in memory. Commented Feb 18, 2015 at 21:02

5 Answers 5

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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

1 Comment

Thanks, this option print all the tuples without (), example tuple (1,1) of the line 1, see like this 1 1 . it's rigth, but print all the tuples of the file, so...I need just print one line for can use this values in a function, and then when the function is done, return to line 2 and do it again. Can you give me some spoor? please
0

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)

Comments

0

Just replace

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

 for t in lst:

with

 for t in f.readlines():

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.