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

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')

This is same as above but does not handle errors:

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

contents = open(filename).read()