The easiest way would be to read the file in as a single string and then split it across your separator:

with open('myFileName') as myFile:
  text = myFile.read()
result = text.split(separator)  # use your \-1 (whatever that means) here

In case your file is very large, holding the complete contents in memory as a single string for using .split() is maybe not desirable (and then holding the complete contents in the list after the split is probably also not desirable). Then you could read it in chunks:

def each_chunk(stream, separator):
  buffer = ''
  while True:  # until EOF
    chunk = stream.read(CHUNK_SIZE)  # I propose 4096 or so
    if not chunk:  # EOF?
      yield buffer
      break
    buffer += chunk
    while True:  # until no separator is found
      try:
        part, buffer = buffer.split(separator, 1)
      except ValueError:
        break
      else:
        yield part

with open('myFileName') as myFile:
  for chunk in each_chunk(myFile, separator='\\-1\n'):
    print(chunk)  # not holding in memory, but printing chunk by chunk
Answer from Alfe on Stack Overflow
Discussions

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
Analyzing string input until it reaches a certain letter on Python - Stack Overflow
I need help in trying to write a certain part of a program. The idea is that a person would input a bunch of gibberish and the program will read it till it reaches an "!" (exclamation mark) so for More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 17, 2011
python - Read file up to a character - Stack Overflow
Edit: The segment terminator character is whatever the 106th byte of the file is. It is not known before the script is invoked. ... Maybe use .read(some_reasonable_number) on the file pointer and search through the result until you find your ~, and if you do, .seek() backwards? More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
๐ŸŒ
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?

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-program-to-read-character-by-character-from-a-file
Python program to read character by character from a file - GeeksforGeeks
September 6, 2024 - Code Explanation: Open a file in read mode that contains a character then use an Infinite while loop to read each character from the file and the loop will break if no character is left in the file to read then Display each character from each ...
๐ŸŒ
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 - Python also makes it easy to read lines of text from a file. Calling in on a file within a for loop will give you the next line of a text fille. Note that the final \n character on the line is included in what is returned.
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
Bytes
bytes.com โ€บ home โ€บ forum โ€บ topic โ€บ python
How do you read up to a specific character in a line of text? - Post.Byes
September 6, 2010 - I have a line of characters that need to be separated. One example is like this: 513413;dialog_513413;Sally Mae has some jobs for you.; Three sets of data all split into three groups placed in one line. What I would like to do is be able to read each group up to the semicolon (obviously without ...
๐ŸŒ
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
The while True loop continues indefinitely until explicitly broken. if char == stop_char: checks if the current character is the target character. If so, break exits the loop. if not char: checks if we've reached the end of the file (an empty string is returned by read() at EOF).
๐ŸŒ
Finxter
blog.finxter.com โ€บ how-to-read-one-character-at-a-time-from-a-file-in-python
How to Read One Character at a Time from a File in Python? โ€“ Be on the Right Side of Change
The lambda function uses read() to read one character at a time. The results of each iteration are output to the terminal. Then, sleep() is called and passed an argument, the number of seconds to delay execution. The iteration continues until all characters in the file have been output to the ...
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-read-file-character-by-character
How to Read a file character by character in Python | bobbyhadz
April 10, 2024 - We used a while True loop to iterate until we reached the end of the file. The file.read() method takes a size argument that represents the number of characters to read from the file.
๐ŸŒ
Java2Blog
java2blog.com โ€บ home โ€บ python โ€บ print string till character in python
Print String Till Character in Python [4 ways] - Java2Blog
November 25, 2022 - A break statement is used to break out of the current loop when encountered. To print string till character in Python, we can iterate over the string and print individual characters. If the specified character is encountered, we can break out of the loop using the break statement.
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ python | split string until character/substring
Python | Split String until Character/Substring - Be on the Right Side of Change
December 15, 2022 - Approach: Use the re.findall method to find all the characters that appear until the last occurrence of the character โ€œ/โ€. To also include the โ€œ/โ€ character in the final string you can specify the pattern within parenthesis which will also include the โ€œ/โ€. In case of the first example ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ how do i read until a specific character so that i can start reading from that location again later.
r/learnprogramming on Reddit: How do I read until a specific character so that I can start reading from that location again later.
December 29, 2019 -

I have a text file where I want to do this:

  • read text into a string

  • if I hit a special character do something accordingly

    • if I hit an * do X with the string

    • if I hit a ~ do Y with the string

  • continue reading from where I left off

  • repeat until EOF

I'm currently using ifstream read, but that just reads until a number of characters, which I can't always know. I know there's getchar, but that reads from input and I want to read from a file. Can anyone help me out?