[python] Easiest way to read/write a file's content in Python

In Ruby you can read from a file using s = File.read(filename). The shortest and clearest I know in Python is

with open(filename) as f:
    s = f.read()

Is there any other way to do it that makes it even shorter (preferably one line) and more readable?

Note: initially I phrased the question as "doing this in a single line of code". As pointed by S.Lott, shorter doesn't necessary mean more readable. So I rephrased my question just to make clear what I meant. I think the Ruby code is better and more readable not necessarily because it's one line versus two (though that matters as well), but also because it's a class method as opposed to an instance method, which poses no question about who closes the file, how to make sure it gets closed even if an exception is raised, etc. As pointed in the answers below, you can rely on the GC to close your file (thus making this a one-liner), but that makes the code worse even though it's shorter. Not only by being unportable, but by making it unclear.

This question is related to python

The answer is


Simple like that:

    f=open('myfile.txt')
    s=f.read()
    f.close()

And do whatever you want with the content "s"


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

***grins***


This is same as above but does not handle errors:

s = open(filename, 'r').read()

contents = open(filename).read()

Slow, ugly, platform-specific... but one-liner ;-)

import subprocess

contents = subprocess.Popen('cat %s' % filename, shell = True, stdout = subprocess.PIPE).communicate()[0]

This isn't Perl; you don't want to force-fit multiple lines worth of code onto a single line. Write a function, then calling the function takes one line of code.

def read_file(fn):
    """
    >>> import os
    >>> fn = "/tmp/testfile.%i" % os.getpid()
    >>> open(fn, "w+").write("testing")
    >>> read_file(fn)
    'testing'
    >>> os.unlink(fn)
    >>> read_file("/nonexistant")
    Traceback (most recent call last):
        ...
    IOError: [Errno 2] No such file or directory: '/nonexistant'
    """
    with open(fn) as f:
        return f.read()

if __name__ == "__main__":
    import doctest
    doctest.testmod()

contents = open(filename)

This gives you generator so you must save somewhere the values though, or

contents = [line for line in open(filename)]

This does the saving to list explicit close is not then possible (at least with my knowledge of Python).


Use pathlib.

Python 3.5 and above:

from pathlib import Path
contents = Path(file_path).read_text()

For lower versions of Python use pathlib2:

$ pip install pathlib2

Then

from pathlib2 import Path
contents = Path(file_path).read_text()

Writing is just as easy:

Path(file_path).write_text('my text')