Home > Back-end >  How to loop certain lines in a text file via starting conditions?
How to loop certain lines in a text file via starting conditions?

Time:01-03

I am trying to solve a coding problem in python, and my pseudocode looks as follows:

x = 0
for line[x] in file:
    if line[x].startswith('>'): 
        next(line)
    while line[x] in file # !startwith('>'): do thing  

What I am trying to accomplish is to skip any lines that start with '>', then for every line after I want to do a thing until the next line starts with a '>'.

I've looked up this question, and other questions I've seen don't talk about the startswith function, and instead talk about using readline() to pull out certain lines. Which is not what I am wanting to do. Can someone point me in a good direction to look?

CodePudding user response:

your first mistake is indexing while in a for loop. You can simply read in a text file, and then loop over each line in it.

In your case, you would want to check that the first char of each line, and based on it's value apply logic to it.

with open("some_file.txt") as f: # opens a text file 
    for line in f:               # loops over each line 
        if line[0] == ">":       # check first char of line
            pass
        else:
             < do something >
  • Related