Read a file using Path.read_text in Python - Good bye with-open-read code

Python Path.read_text function can substitute the traditional with-open way.

from pathlib import Path

p = Path(__file__).parent / 'data' / 'a.html'
c = p.read_text()

# /Users/serif/python/test/data/a.html

<!DOCTYPE html>
<html lang="en">

p is a PosixPath object representing the path of a.html. Once you get the path object, you can read the content without with statement.

read_text is very useful and supported from Python 3.5. Avoid writing with-open-read code only to read files.

Python File

Python Tutorial