Coder Perfect

How do you read a text file into a string variable while removing newlines?


To read a file in Python, I use the following code segment:

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

Input file is:


I also receive an error when I print data.


As far as I can tell, the data is in a list format. What’s the best way to make it string? Also, how can I get rid of the “n”, “[“, and “]” characters?

Asked by klijo

Solution #1

You could use:

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

Alternatively, if the content of the file is guaranteed to be one-line,

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

Answered by sleeplessnerd

Solution #2

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

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

After that, you may remove the newlines with str.replace:

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

Answered by Jonathan Sudiaman

Solution #3

In one line, you can read from a file:

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

Please note that this does not explicitly close the file.

As part of the trash collection process, CPython will close the file when it exits.

Other Python implementations, on the other hand, will not. It is preferable to utilize with or explicitly close the file when writing portable code. It is not always true that shorter is better. See for further information.

Answered by Nafis Ahmad

Solution #4

I usually use: to unite all lines into a string and eliminate new lines.

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

Answered by Pedro Lobito

Solution #5

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.

Answered by MagerValp

Post is based on