Read a file until a specific Character in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. Read a file until a specific Character in Python
  2. Read a file until a specific Character using a while loop

# Read a file until a specific Character in Python

To read a file until a specific character:

  1. Open the file in reading mode.
  2. Use the file.read() method to read the file's contents into a string.
  3. Use the str.split() method to split the file on the given character.
  4. Access the list at index 0.
main.py
with open('example.txt', 'r', encoding='utf-8') as file: contents = file.read() character = '!' result = contents.split(character) print(result) # 👉️ ['bobby\nhadz\n.com\n', '\none\ntwo\nthree'] # bobby # hadz # .com print(result[0])

read file until specific character

If you are working with very large files, scroll down to the next subheading.

The code sample assumes that you have an example.txt file located in the same directory.

example.txt
bobby hadz .com ! one two three
The code for this article is available on GitHub

We used the with statement to open the file in reading mode.

The statement automatically takes care of closing the file for us.

The file.read() method is used to read the contents of the entire file into a string.

If you work with very large files that you don't want to load in memory, scroll down to the next subheading.

Once we have the file's contents stored in a string, we use the str.split() method to split the string on the given character.

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

# Only getting the part of the file before the character

If you only need the part of the file before the character, set the maxsplit() argument to 1 to only split the string once.

main.py
with open('example.txt', 'r', encoding='utf-8') as file: contents = file.read() character = '!' result = contents.split(character, 1) print(result) # 👉️ ['bobby\nhadz\n.com\n', '\none\ntwo\nthree'] # bobby # hadz # .com print(result[0])

only getting part of file before the character

The code for this article is available on GitHub

This is a bit more performant if the character is contained multiple times in the file because the string is only split on the first occurrence of the given character.

Alternatively, you can use a while loop.

# Read a file until a specific Character using a while loop

This is a three-step process:

  1. Open the file in reading mode.
  2. Use the file.read(1) method to read the file character by character in a while loop.
  3. Once the stop character is found, exit the loop.
main.py
with open('example.txt', 'r', encoding='utf-8') as file: result = '' stop_char = '!' while True: char = file.read(1) if char == stop_char: break if not char: print('Reached end of file') break result += char # bobby # hadz # .com print(result)

read file until specific character using while loop

The code sample assumes that you have an example.txt file located in the same directory.

example.txt
bobby hadz .com ! one two three
The code for this article is available on GitHub

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.

If you are reading a file in binary mode, then size represents the size of bytes to be read from the file.

We set the size argument to 1 to read the file character by character.

If the end of the file has been reached, the file.read() method returns an empty string.

On each iteration, we check if the current character is equal to the stop character.

If the condition is met, we exit the loop, otherwise, we add the character to the result string.

The break statement breaks out of the innermost enclosing for or while loop.

I've also written an article on how to read a file character by character.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.