Today I learned you can use
pathlib to read the contents of a file.
is an amazing module from the Python 3 Standard Library.
I have been tweeting about
pathlib and recently I shared a mini cookbook
The Python 🐍 Standard Library is one of the reasons I love 💙 Python.— Rodrigo 🐍📝 (@mathsppblog) November 6, 2021
📂🔍 dealing with your filesystem is super simple.
All you have to do is use the `pathlib` module.
This short thread is a mini `pathlib` cookbook 🍳, showing some example usages of `pathlib`.
Ready 🚀? pic.twitter.com/kWacRATY1w
Adam Johnson proceeded to comment on that thread,
telling me about two methods I didn't know:
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
This is just some text!
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,
.read_text method only returns
"\n" for newlines
"\r\n" on each newline
(I'm using a Windows machine).
That's it for now! Stay tuned and I'll see you around!
I hope you learned something new! If you did, consider following the footsteps of the readers who bought me a slice of pizza 🍕. Your small contribution helps me produce this content for free and without spamming you with annoying ads.