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

1073

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?

This question is tagged with python string

~ Asked on 2011-12-03 16:47:54

The Best Answer is


1495

You could use:

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

~ Answered on 2011-12-03 17:06:34


87

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

~ Answered on 2015-12-03 02:52:56


Most Viewed Questions: