Today I learned you can use pathlib to read the contents of a file.

Photo by Mr Cup / Fabien Barral on Unsplash

Reading files with pathlib

pathlib is an amazing module from the Python 3 Standard Library.

I have been tweeting about pathlib and recently I shared a mini cookbook on it:

Adam Johnson proceeded to comment on that thread, telling me about two methods I didn't know: .read_text and .read_bytes.

As it turns out, pathlib.Path can also be used to read the full contents of a file!

Here is an example text file I have in C:/tmp/foo.txt:

This
is

just
some
text!

Using pathlib to read it is easy:

>>> from pathlib import Path
>>> Path("C:/tmp/foo.txt").read_text()
'This\nis\n\njust\nsome\ntext!'
>>> Path("C:/tmp/foo.txt").read_bytes()
b'This\r\nis\r\n\r\njust\r\nsome\r\ntext!'

It's interesting to notice, above, how the .read_text method only returns "\n" for newlines but .read_bytes returns "\r\n" on each newline (I'm using a Windows machine).

That's it for now! Stay tuned and I'll see you around!

Become a better Python 🐍 developer πŸš€

+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!

My book β€œPydon'ts” teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here πŸπŸš€.

Previous Post Next Post

Blog Comments powered by Disqus.