Coder Perfect

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

Problem

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

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

Input file is:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

I also receive an error when I print data.

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

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 = file.read().replace('\n', '')

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

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

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 https://stackoverflow.com/a/7396043/362951 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 https://stackoverflow.com/questions/8369219/how-to-read-a-text-file-into-a-string-variable-and-strip-newlines