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

Sample query:

I use the following code segment to read a file in python:

with open ("data.txt", "r") as myfile:

Input file is:


and when I print data I get


As I see data is in list form. How do I make it string? And also how do I remove the "\n""[", and "]" characters from it?

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

You could use:

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

Or if the file content is guaranteed to be one-line

with open('data.txt', 'r') as file:
    data =

Answer #2:

In Python 3.5 or later, using pathlib you can copy text file contents into a variable and close the file in one line:

from pathlib import Path
txt = Path('data.txt').read_text()

and then you can use str.replace to remove the newlines:

txt = txt.replace('\n', '')

Answer #3:

You can read from a file in one line:

str = open('very_Important.txt', 'r').read()

Please note that this does not close the file explicitly.

CPython will close the file when it exits as part of the garbage collection.

But other python implementations won’t. To write portable code, it is better to use with or close the file explicitly.

Answer #4:

To join all lines into a string and remove new lines, I normally use :

with open('t.txt') as f:
  s = " ".join([l.rstrip() for l in f]) 

with open("data.txt") as myfile:
    data="".join(line.rstrip() for line in myfile)

join() will join a list of strings, and rstrip() with no arguments will trim whitespace, including newlines, from the end of strings.

Answer #5:

I’m surprised nobody mentioned splitlines() yet.

with open ("data.txt", "r") as myfile:
    data =

Variable data is now a list that looks like this when printed:


Note there are no newlines (\n).

At that point, it sounds like you want to print back the lines to console, which you can achieve with a for loop:

for line in data:

Answer #6:

I have fiddled around with this for a while and have prefer to use use read in combination with rstrip. Without rstrip("\n"), Python adds a newline to the end of the string, which in most cases is not very useful.

with open("myfile.txt") as f:
    file_content ="\n")

Hope you learned something from this post.

Follow Programming Articles for more!

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →