files are iterators (unlike lists) so you can just make a second for loop: with open(inputfile, 'r') as infile: for line in infile: if line.startswith(">"): print line, # comma on the end prevents the double spacing from printing a file line for line in infile: print line, if line.startswith(">"): break # stop this inner for loop; outer loop picks up on the next line Edit: I get the feeling I don't understand your problem. Can you show some example data and what you want out? Answer from novel_yet_trivial on reddit.com
🌐
Reddit
reddit.com › r/learnpython › read file until string match?
r/learnpython on Reddit: Read file until string match?
February 1, 2017 -

I have this code:

with open(inputfile, 'r') as infile:
    for line in infile:
        if line.startswith(">"):
            print line
            # keep printing until next ">" encountered; stop at that point
            # and move on to next line that starts with ">"...

But I don't know how to do that last part...keep printing lines in the file until I hit the next ">", at which point I need it to stop printing, find the next line that starts with ">", then start printing again.

I've searched like every google link for this. It has been asked a lot, but nowhere is there an explanation understand. Usually it's also some variation, such as print from the start until match, but I know how to do that. I need to print from match to match...

I think I can do this with enumerate() a list, and a while loop, but it requires I read the file into memory, which I don't want to do considering the files I need to work on are a few GB each and contain a few million lines, so I don't want to read the entire thing into a list...

The real problem I am having is how to access the "next line" after the line that contains ">"? next(infile) works, but only for the immediate next line. What if I need the next 2 or 3 lines? I tried the following inside the "if line.startswith" part:

line = next(infile)
while not line.startswith(">"):
    print line
    line = next(infile)

But that doesn't work...(not entirely sure why, I assume next() can only take the immediate next line).

Anyone? Is there no default python function (that I can't find) that does this?

check file for string then read line by line Feb 4, 2023
r/learnpython
3y ago
return nth line from a txt file using for loop? Sep 23, 2022
r/learnpython
3y ago
How do I read a file line by line? Apr 26, 2017
r/learnpython
9y ago
Reading regex pattern from a file Apr 9, 2021
r/learnpython
5y ago
How to deal with text files on an advanced level Mar 29, 2025
r/learnpython
last yr.
More results from reddit.com
🌐
Bobby Hadz
bobbyhadz.com › blog › python-read-file-until-specific-character
Read a file until a specific Character in Python | bobbyhadz
April 10, 2024 - Read a file until a specific Character in Python · Read a file until a specific Character using a while loop · To read a file until a specific character: Open the file in reading mode. Use the file.read() method to read the file's contents ...
Discussions

regex - Read file until specific line in python - Stack Overflow
I have one text file. I am parsing some data using regex. So open the file and read it and the parse it. But I don't want to read and parse data after some specific line in that text file. For exam... More on stackoverflow.com
🌐 stackoverflow.com
Reading a file until a specific character in python - Stack Overflow
I am currently working on an application which requires reading all the input from a file until a certain character is encountered. ... Every time strip encounters \n, it is removed from the input and treated as a string in list c. More on stackoverflow.com
🌐 stackoverflow.com
python 3.x - Reading txt file till certain point and then create new txt file out of existing file - Software Engineering Stack Exchange
I have a txt file from where I want to create new files based on the data which is up to '$'character. My input file looks like: string1 string2 string3 $string4 string5 $string6 string7 ... (and s... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
September 12, 2020
text - Read Up Until a Point Python - Stack Overflow
I have a text file full of data that starts with #Name #main then it's followed by lots of numbers and then the file ends with #extra !side So here's a small snippet #Name #main 60258960 33031... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Program Creek
programcreek.com › python
Python read until
def read_until(self, match, timeout=None): """Read until a given string is encountered or until timeout. When no match is found, return whatever is available instead, possibly the empty string. Raise EOFError if the connection is closed and no cooked data is available.
🌐
Stack Exchange
softwareengineering.stackexchange.com › questions › 415829 › reading-txt-file-till-certain-point-and-then-create-new-txt-file-out-of-existing
python 3.x - Reading txt file till certain point and then create new txt file out of existing file - Software Engineering Stack Exchange
September 12, 2020 - Some extensions you could do: have comment lines which start with #; use the split method of string to have comments that can start anywhere on the line; use the re module to remove lines that are all blanks; make the script into a function ...
Find elsewhere
🌐
PyTutorial
pytutorial.com › read-string-until-character-in-python
PyTutorial | Read String Until Character in Python
February 11, 2025 - The split() method is a simple way to read a string until a specific character. It splits the string into a list based on the delimiter.
🌐
Post.Byes
post.bytes.com › home › forum › topic › python
How do you read up to a specific character in a line of text? - Post.Byes
I am aware of string.read(siz e), but obviously size is needed and it is variable. Highly prefer having size given also.
🌐
GeeksforGeeks
geeksforgeeks.org › python-string-till-substring
Python - String till Substring - GeeksforGeeks
January 16, 2025 - We can manually iterate through the string and stop when we encounter the substring. ... s = "learn-python-with-gfg" sub = "-" res = "" for c in s: # Iterating through each character in the string if c in sub: # Stop when the substring is found break res += c # Add characters to the result print(res)
🌐
Tutorial Reference
tutorialreference.com › python › examples › faq › python-how-to-read-file-until-a-specific-character
How to Read a File Until a Specific Character in Python | Tutorial Reference
result += char: Appends the current character to the result string. This approach is memory-efficient because it processes the file one character at a time. Reading Until a Character with split() (for smaller files)
🌐
Microsoft MakeCode
makecode.microbit.org › reference › serial › read-until
read Until
Read a text from the serial port until a delimiter is found. ... The following example reads strings separated by commands (,).
🌐
O'Reilly
oreilly.com › library › view › python-in-a › 0596001886 › re851.html
read_until - Python in a Nutshell [Book]
March 3, 2003 - Nameread_untilSynopsis t.read_until(expected,timeout=None) Reads data from the connection until it encounters string expected, or until timeout seconds elapse when timeout is not... - Selection from Python in a Nutshell [Book]
Author   Alex Martelli
Published   2003
Pages   656
🌐
Reddit
reddit.com › r/learnpython › issues reading from serial port using read_until()
r/learnpython on Reddit: Issues reading from serial port using read_until()
December 17, 2020 -

First time posting here, I think I posted the "code" part correctly but didn't know about the output part.

I created a class to help me read and write into an instrument using serial port. However, recently I found an issue that I think it's due to sending multiple write commands and I only need to read when I query the instrument. When I send regular write commands, the instrument outputs text indicating the changes made as shown below:

    self.id.write(str.encode("send write command\r"))
    time.sleep(1)
    self.id.write(str.encode("get status\r"))
    output=self.id.read_until(str.encode(">>\r"))

When sending the write command, it will output a status as:

>>write command:

Configured state to: 0A

>>

>>get status

status is configured to: BB

What I think it's happening is that when I use the read_until() , it will start reading from the "send write" command instead of the "get status" because when I look at the text captured it corresponds to the "Configured state to: 0A" line.

My question is: How do I get the code to read only from the time I send the "get status" command? I have thought about reading the line when I send the "write command" and not doing anything with it, but I think there might be another option.