Rodrigo ๐Ÿ๐Ÿš€ Profile picture
Take your Python ๐Ÿ skills to the next level ๐Ÿš€!

Nov 6, 2021, 11 tweets

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.

Keep scrolling