I use the following code segment to read a file in python:
with open (\"data.txt\", \"r\") as myfile:
data=myfile.readlines()
Input fil
Have you tried this?
x = "yourfilename.txt"
y = open(x, 'r').read()
print(y)
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', '')
I have fiddled around with this for a while and have prefer to use use read
in combination with rstrip
. Without rstrip("\n")
, Python adds a newline to the end of the string, which in most cases is not very useful.
with open("myfile.txt") as f:
file_content = f.read().rstrip("\n")
print file_content
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
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()
You can also strip each line and concatenate into a final string.
myfile = open("data.txt","r")
data = ""
lines = myfile.readlines()
for line in lines:
data = data + line.strip();
This would also work out just fine.