tags:

views:

355

answers:

1
+4  Q: 

Python File Slurp

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?

+28  A: 
f = open('x.txt').read()

if you want a single string, or

f = open('x.txt').readlines()

if you want a list of lines. Both don't guarantee the file is immediately closed (in practice it will be immediately closed in current CPython, but closed "only when the garbage collector gets around to it" in Jython, IronPython, and probably some future version of CPython).

A more solid approach (in 2.6+, or 2.5 with a from __future__ import with_statement) is

with open('x.txt') as x: f = x.read()

or

with open('x.txt') as x: f = x.readlines()

This variant DOES guarantee immediate closure of the file right after the reading.

Alex Martelli
That's what I would have guessed, but didn't know when the opened file would be closed. Thanks!
Mike Caron