Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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?

like image 542
klijo Avatar asked Dec 03 '11 16:12

klijo


People also ask

How do I read a text file to a string variable?

The file read() method can be used to read the whole text file and return as a single string. The read text can be stored into a variable which will be a string. Alternatively the file content can be read into the string variable by using the with statement which do not requires to close file explicitly.

How do I read the contents of a file line by line?

The line must be terminated by any one of a line feed ("\n") or carriage return ("\r"). In the following example, Demo. txt is read by FileReader class. The readLine() method of BufferedReader class reads file line by line, and each line appended to StringBuffer, followed by a linefeed.


2 Answers

You could use:

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

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

with open('data.txt', 'r') as file:     data = file.read().rstrip() 
like image 108
sleeplessnerd Avatar answered Sep 23 '22 00:09

sleeplessnerd


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', '') 
like image 43
Jonathan Sudiaman Avatar answered Sep 19 '22 00:09

Jonathan Sudiaman