The Python ๐ Standard Library is one of the reasons I love ๐ Python.
๐๐ 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 ๐?
๐ Creating a `Path` object
`Path` objects are the bread and butter of `pathlib`.
Here, I just create a path with no arguments, which defaults to the path `.`
Notice how I used `Path` but I get a `WindowsPath` back.
`pathlib` automatically detects your OS ๐
๐ Getting the parent
The `parent` attribute returns the logical parent of the path you have at hands ๐
๐ Navigating with `/`
The `/` is the operator for division, right?
But, with paths, you can use it to navigate to other paths ๐
(Use `/` regardless of the OS you are on.)
๐ Resolving a path
Paths have a `.resolve` method that resolves the path.
This resolves any symlinks, and is the only way to โget rid ofโ the `..` in paths ๐
๐ Going up the filesystem
If you don't want to write a bunch of `.parent` to go up the filesystem, you can also use `/ ".."` and `.resolve`:
๐ Check file/directory existence
With the `.exists` method, you can check if the path points to a resource that exists in the filesystem.
This example ๐ should help you figure out what I have on my `C:/tmp` folder.
๐ Check for valid directories
This is similar to `.exists`, but only returns `True` for directories that exist.
๐ Accessing folder relative to script
Imagine you have this structure:
| - project/
| - data/
| - data1.csv
| - data2.csv
| foo.py
Using `__file__`, you can get to the `data` folder ๐
This is independent from the current working dir! ๐ฅ
That's it for this mini cookbook thread!
If you enjoyed, let me know, and I'll write more about `pathlib` in the near future!
If you want to learn more about Python ๐, follow @mathsppblog.
You won't be disappointed.
Here are some cool things we learned ๐
๐ Creating a `Path` object
๐ Navigating with `/`
๐ Check file/directory existence
๐ Accessing folder relative to script
See you around ๐
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.