DEV Community 👩‍💻👨‍💻

qoqosz
qoqosz

Posted on

Python one-liner for reading files

I was today years old when I realized that instead of a lengthy open context manager:

with open('myfile.txt') as f:
    print(f.read())
Enter fullscreen mode Exit fullscreen mode

I can use read_text():

from pathlib import Path

print(Path('myfile.txt').read_text())
Enter fullscreen mode Exit fullscreen mode

Of course, if you factor in the extra import it is no longer a one-liner. Anyway, it was a nice little discovery for me.

Top comments (0)

🌚 Life is too short to browse without dark mode