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 =
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()
with open('x.py') as f: s = f.read()
***grins***
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')
contents = open(filename).read()
This is same as above but does not handle errors:
s = open(filename, 'r').read()
If you're open to using libraries, try installing forked-path (with either easy_install or pip).
Then you can do:
from path import path
s = path(filename).bytes()
This library is fairly new, but it's a fork of a library that's been floating around Python for years and has been used quite a bit. Since I found this library years ago, I very seldom use os.path
or open()
any more.