DB7 DB7 - 1 month ago 5
Python Question

Python: How to create a loop that depending on values of a list sends sections of a separate file, to one of two output files?

I have a list with two values, either yes or no. And a sequence which is a list of strings, depending on whether the list says yes or no, I want to send 8 consecutive lines of the sequence file into one of two text files (yes.txt and no.txt) depending on what the list said, and loop this for every item in the list.

Answer

assuming that sequence is a list of lines from a sequence document you could try the following

for i in range(0, len(YesOrNo)):
    start = i + (7*i)
    end = 8 * (i+1)
    if YesOrNo[i] == 'yes':
        Y.writelines(sequence[start:end])
    elif YesOrNo[i] == 'no': 
        X.writelines(sequence[start:end])

I am using writelines because I am assuming that sequence is list of stings, you could also use write and just replace sequence with "\n".join(sequence[start:end]