How do I read a text file into a string variable in Python starting at the second line?

15.6k views Asked by At

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.

1

There are 1 answers

7
Ethan Bierlein On BEST ANSWER

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.

with open("/path/to/myfile.txt", "rb") as myfile:
     data_to_read = "".join(myfile.readlines()[1:])
     ...

The advantage of using a with ... as construct is that the file is explicitly closed, and you don't need to call myfile.close().