Is there a one-liner to read all the lines of a file in Python, rather than the standard:
f = open('x.txt')
cts = f.read()
f.close()
Seems like this is done so often that there’s got to be a one-liner. Any ideas?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This will slurp the content into a single string in Python 2.61 and above:
And this will create a list of lines:
These approaches guarantee immediate closure of the input file right after the reading.
Footnote:
from __future__ import with_statement.An older approach that does not guarantee immediate closure is to use this to create a single string:
And this to create a list of lines:
In practice it will be immediately closed in some versions of CPython, but closed “only when the garbage collector gets around to it” in Jython, IronPython, and probably some future version of CPython.