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?
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.
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.
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()
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', '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With