
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()
print(p.as_posix())
# /Users/serif/python/test/data/a.html
print(c)
'''
<!DOCTYPE html>
<html lang="en">
<head><title>Title</title></head>
<body></body>
</html>
'''
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.
Comments
Powered by Markdown