Advertisement
Advertisement


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


Question

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

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

Input file is:

LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN
GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE

and when I print data I get

['LLKKKKKKKKMMMMMMMMNNNNNNNNNNNNN\n', 'GGGGGGGGGHHHHHHHHHHHHHHHHHHHHEEEEEEEE']

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?

2020/02/04
1
990
2/4/2020 8:05:13 AM

Accepted Answer

You could use:

with open('data.txt', 'r') as file:
    data = file.read().replace('\n', '')
2019/03/30
1369
3/30/2019 1:26:48 PM

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. Short is not always better. See https://stackoverflow.com/a/7396043/362951

2018/05/08

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

with open('t.txt') as f:
  s = " ".join([x.strip() for x in f]) 
2020/07/17

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', '')
2019/02/25

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.

2011/12/03

This can be done using the read() method :

text_as_string = open('Your_Text_File.txt', 'r').read()

Or as the default mode itself is 'r' (read) so simply use,

text_as_string = open('Your_Text_File.txt').read()
2019/02/26

Source: https://stackoverflow.com/questions/8369219
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]