The module pathlib
is around since Python 3.4 but I must confess that I’ve started to use it a short time ago. For those who are listening this name for the first time, pathlib
is an Object-oriented filesystem paths module; in other words, a module with few classes to help you to manipulate paths in a pratical way.
Each class has a proper use and if you wanna dive into it, I suggest to take a look in the docs. This post is introductory (and at the same time, a reminder to myself :)).
Let the games begin!
Just import:
from pathlib import Path
If you would like to create a new instance of Path
(or represent a path), you just have to add the path to the object constructor:
>>> Path('/home/ana.gomes')
PosixPath('/home/ana.gomes')
In this case is returning a PosixPath
that represents a no-Windows file system. If your OS is Windows, it will return a WindowsPath
. Both classes implements concrete paths.
To concatenate, it’s much better now:
>>> myfile = Path.home() / 'myfile.txt'
>>> myfile
PosixPath('/Users/ana.gomes/myfile.txt')
You just need the slashs!
With a Path
instance, is possible to have access to many handy methods, like:
Path.cwd()
Path.is_dir()
Path.is_file()
Path.exists()
Path.samefile()
Path.owner()
Path.home()
Path.parts()
If you are wondering about a file extension, you can use suffix
or suffixes
(for a list of it).
Another cool thing is to know the relative path given a directory. For instance:
>>> myfile = Path.home() / 'myfile.txt'
>>> myfile
PosixPath('/Users/ana.gomes/myfile.txt')
>>> myfile.relative_to('/Users/')
PosixPath('ana.gomes/myfile.txt')
Last but not least, how to list directories and walk through it. To list, we can use glob
:
>>> list((Path.home() / 'Documents').glob('**/*.*'))
[PosixPath('/Users/ana.gomes/Documents/.localized'), PosixPath('/Users/ana.gomes/Documents/myfile.txt')]
Using **
, it will walk recursivelly.
To iterate, use iterdir
.
>>> list((Path.home() / 'personal-workspace').iterdir())
[PosixPath('/Users/ana.gomes/personal-workspace/.DS_Store'), PosixPath('/Users/ana.gomes/personal-workspace/dotfiles'), PosixPath('/Users/ana.gomes/personal-workspace/pass2dashlane'), PosixPath('/Users/ana.gomes/personal-workspace/speakerfight'), PosixPath('/Users/ana.gomes/personal-workspace/sandbox'), PosixPath('/Users/ana.gomes/personal-workspace/blog-engine'), PosixPath('/Users/ana.gomes/personal-workspace/looong'), PosixPath('/Users/ana.gomes/personal-workspace/20-texts-in-my-pocket')]
In this case, it’s not possible to walk recursivelly.
Well, this was the first micro post (a little drop) about Python. If you know about other cool ways to use Pathlib
, just drop a line. :) See ya!
Translations
comments powered by Disqus