46

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?

Mike Caron
  • 5,674
  • 4
  • 48
  • 71
  • 18
    Funny, I needed this again and I googled for it. Never thought my own question would come up :) – Mike Caron May 10 '11 at 15:23
  • I also keep finding this when I am actually looking for http://stackoverflow.com/questions/1450393/how-do-you-read-from-stdin-in-python – tripleee Feb 06 '14 at 10:47

3 Answers3

109

This will slurp the content into a single string in Python 2.61 and above:

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

And this will create a list of lines:

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

These approaches guarantee immediate closure of the input file right after the reading.

Footnote:

  1. This approach can also be used in Python 2.5 using from __future__ import with_statement.

An older approach that does not guarantee immediate closure is to use this to create a single string:

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

And this to create a list of lines:

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

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.

Alan W. Smith
  • 24,647
  • 4
  • 70
  • 96
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
10

Starting in Python 3.5, you can use the pathlib module for a more modern interface. Being Python 3, it makes a distinction between reading text and reading bytes:

from pathlib import Path

text_string = Path('x.txt').read_text()  # type: str

byte_string = Path('x.txt').read_bytes()  # type: bytes
drhagen
  • 8,331
  • 8
  • 53
  • 82
1

If you are on Python3, make sure you properly respect your file's input encoding, e.g.:

import codecs
with codecs.open(filename, 'r', encoding="utf8") as file:
    cts = file.read()

Find the list of codec names in the Python3 codec list. (The mechanism is also advisable for Python2 whenever you expect any non-ASCII input)

Lutz Prechelt
  • 36,608
  • 11
  • 63
  • 88
  • 4
    Some people may consider the encoding issue to be off-topic. Also, my code is not minimal: using the builtin`open` as in `open(filename, 'r', encoding='utf8')` would save the import statement and make the answer a better fit with the question. – Lutz Prechelt Dec 10 '15 at 09:44
  • I've put the improvement by @LutzPrechelt into the main answer (and made it a one-liner as originally requested). I expect people won't downvote it now. – Eponymous May 27 '18 at 20:22