Read a text file into string and strip newlines in Python

In this article, we will learn to read a text file into a string variable and strip newlines.

Table Of Contents

Strip newlines means removing the \n from last of the string. To open a file in python , we use open() method.It returns a file object.

SYNTAX of open():

open(file, mode)

It recieves only two parameters :
– Path or name of the file you want to open.
– The mode in which you want to open that particular file.

Advertisements

See this code below :

CODE :

with open('example.txt','r') as file:
    text = file.readlines()
    print(type(text))
    print(text)

OUTPUT :

<class 'list'>
['This is the first line.\n', 'This is the second line.\n', 'This is the third line\n', 'This is the fouth line.\n', 'This is the fifth line.\n']

As you can see in output, Text in file example.txt gets printed in a list and after every line there is \n which is called newline. Data type of variable text is also a list type.

The contents of our example.txt is,

This is the first line.
This is the second line.
This is the third line
This is the fouth line.
This is the fifth line.

Create a example.txt file and save at same location where your code file is. Now we will read about different methods. Read and try this code on your machine. I have used Python version Python 3.10.1.

Read a text file into a string and strip newlines using file.read() and replace()

In the problem above, you can see readlines() method has been used to read the data. But now we will use read() method. The read() method iterates over every single character, that means read() method reads character wise. Then using the replace() function, we can replace all occurrences of ‘\n’ with an empty string.

EXAMPLE :*

with open('example.txt','r') as file:
    text = file.read().replace('\n', ' ')
    print(type(text))
    print(text)

OUTPUT :

<class 'str'>
This is the first line. This is the second line. This is the third line This is the fouth line. This is the fifth line.

Now you can see, by using read() and replace(), we have sucessfully removed the \n and saved all the data from a text file to a single string object.

Read a text file into a string and strip newlines using rstrip()

The rstrip() method is another method through which we can strip newlines in python string.

What is rstrip() method ?

The rstrip() method removes any whitespace or new line characters which from the end of a line. It recieves only one optional parameter, which is the specific character that you want to remove from the end of the line.

EXAMPLE :

with open('example.txt','r') as file:
    text = file.read().rstrip()
    print(type(text))
    print(text)

OUTPUT :

<class 'str'>
This is the first line.
This is the second line.
This is the third line
This is the fouth line.
This is the fifth line.

In output above you can see data type is of type str and there is no any \n. Unlike repalce() method all the names are also in different lines.
There is also a similar to rstrip() method which is strip(). The strip() method removes characters from both sides (starting and beginning of a line).

Read a text file into a string and strip newlines using List Comprehension

Iterate over each line of file and strip the newline characters from the end of each line. Then join all these lines back to a single string.

Example:

with open('example.txt','r') as file:
    text = " ".join(line.rstrip() for line in file)
    print(text)

Output:

This is the first line. This is the second line. This is the third line This is the fouth line. This is the fifth line.

Summary

So we read about three different methods, to read a text file into a string variable and strip newlines in python. You can use all three different methods from above depending upon your use but the easiest and most commonly used is read() method. Because it reads characterwise and removes the newlines from the given string file. rstrip() and strip() methods are also used when you have any specific characters you want to remove.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top