I use the following code segment to read a file in python
file = open("test.txt", "rb")
data=file.readlines()[1:]
file.close
print data
However, I need to read the entire file (apart from the first line) as a string into the variable data
.
As it is, when my files contents are test test test
, my variable contains the list ['testtesttest'].
How do I read the file into a string?
I am using python 2.7 on Windows 7.
The solution is pretty simple. You just need to use a
with ... as
construct like this, read from lines 2 onward, and then join the returned list into a string. In this particular instance, I'm using""
as a join delimiter, but you can use whatever you like.The advantage of using a
with ... as
construct is that the file is explicitly closed, and you don't need to callmyfile.close()
.