Ditch "os.path" and master Python's pathlib module today:
Pathlib is a Python module that turns file system paths into easy-to-manage objects, making your code cleaner and more intuitive.
Today, I'll explain everything you need to know about pathlib!
Let's go! 🚀
1️⃣ Importing
Pathlib comes as a builtin module in python, here's how you import it:
2️⃣ Creating Paths
Instead of dealing with file path strings, `pathlib` allows you to create path objects easily. Here's how you can define a path to your home directory:
3️⃣ Navigating with Paths
`pathlib` makes navigating through directories a breeze. Use the `/` operator to join paths intuitively:
4️⃣ Checking Path Existence
Before you perform any file operations, you can check if the path exists:
5️⃣ Reading & Writing Files
`pathlib` simplifies file operations. Here's how to write and then read from a file:
6️⃣ Listing Directory Contents
List all files in a directory with `iterdir`, and filter them easily with comprehensions:
8️⃣ Path Properties & working with parts of path
`pathlib` makes it easy to access path properties & different parts of a path, such as the parent directory, name of the file, or its suffix & more...
9️⃣ Getting File Size
You can call .stat() method on a Path object & it retrieves:
• File size
• Permissions
• Modification time
• Owner and group IDs
Here's how we can get file size using this:
If you're interested in:
- Python 🐍
- ML/AI Engineering ⚙️
Find me → @akshay_pachaar ✔️
Enjoyed this tutorial❓
Check out my book on Python: bit.ly/InstantPython
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.