Fernanda Costa
Fernanda Costa

Reputation: 85

issues in printing next() in python 3

I'm having a weird issue with the command print(next()) in python 3.

When i use it to print on the console, it works perfectly, but when i try to save the output into a file, it doesn't work! The commands that i'm using are the following:

for item in final:
    fasta = open(fname) # fname is the name if input file
    for line in fasta:
        line = line.strip()
        if item in line:
            item = item.strip()
            print('Line:', line, '\nNext line:', next(fasta)) # this works perfectly!
            print(line, next(fasta), file=open('finalList.fa', "a")) # this one doesn't work!

The output that I get from the last command's next(fasta) part is the line+2 instead of line+1, like the one I get from the print on console command.

Does anyone has a clue about what is going on? Any tip will be very much appreciated!

Upvotes: 1

Views: 181

Answers (3)

Fernanda Costa
Fernanda Costa

Reputation: 85

I just realized that when you call next() command in python 3 it reads correctly line+1 and when i call it again, it will consider line the next(line) instead of line, so it prints next(next(line) which is line+2!

So i fixed it with just removing the print in the console command line.

Thank you all and sorry about the noob problem!

Upvotes: 1

Carcigenicate
Carcigenicate

Reputation: 45742

Calling next advances the given iterator (fasta in this case). Calling it multiple times will advance it multiple times and cause elements to be skipped. You need to save the return value in a variable if you want to use the data in different places:

if item in line:
    data = next(fasta) # Save it here
    item = item.strip()
    print('Line:', line, '\nNext line:', data) # Then use it multiple times here and below
    print(line, data, file=open('finalList.fa', "a"))

Upvotes: 2

yoadev
yoadev

Reputation: 146

Did you tried to create a variable and pass the value of next(foo) in this variable, and finally print the variable ?

Upvotes: 1

Related Questions