W3docs

How to read a text file into a string variable and strip newlines?

In Python, you can read a text file into a string variable and strip newlines using the following code:

In Python, you can read a text file into a string variable and strip newlines using the following code:

Read a text file into a string variable and strip newlines

with open("file.txt", "r") as file:
    data = file.read().replace('\n', '')

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

The open() function is used to open the text file, and the "r" parameter specifies that the file should be opened in read mode. The with statement is used to ensure that the file is properly closed after it is read. The .read() method is used to read the contents of the file into a string variable. The .replace('\n', '') method is used to remove newline characters from the string.