How to read a text file into a string variable and strip newlines?
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:
and when I print data I get
As I see data is in
list form. How do I make it string? And also how do I remove the
"]" characters from it?
You could use:
with open('data.txt', 'r') as file: data = file.read().replace('\n', '')
Read more... Read less...
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
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])
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.
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()