r/learnpython • • Mar 20 '19

Pathlib and why you should try it.

So here I was over the last week or so working on a project. Finally, it was finished. I had it working. I just needed to bug test and clean up code. So I gave it to a friend of mine to do some code review (Whos a much better programmer than I am at this point.). He noticed the asinine way I was handling paths, which is the way that I have and many others I knew of had been handling paths in Python for, well since forever, and suggested I swap it all out and use Pathlib instead. And man was it a night and day difference.

Suddenly doing something like:

path = "/etc/configDir" +"/"+ "myProgramConfig.cfg"

Becomes as simple as:

path = configDir / myProgram    

Even better, its portable. See I was writing a script for both Windows and Nix, which means I had to handle paths accordingly. Well you see, Pathlib handles paths as objects, and it converts them on the fly for you in the background. So when you go:

path = Path(r'/etc/this/is/my/path')  OR path = Path(r'c:\windows\this\is\my\path') 

It converts the object into a proper Windows or Posix path object for you, and whenever you use the / operator, it knows that you mean to append a path. You can even do things like:

path2 = Path(r'/etc/this/is/my/path')
path3 = path2 / "mySubdir" / "myfile.txt" 
print(path3) 
    > '/etc/this/is/my/path/mySubdir/myfile.txt'
print(path3.parent)
    > '/etc/this/is/my/path/mySubdir'
print(path3.name)
    > 'myfile.txt'
print(path3.suffix)
    > '.txt'
print(path3.stem)
    > 'myfile'

There is also the cool idea that this was made specifically to put all of your filesystem methods/functions in one place. So with a path object you can now test if it exists, make a directory, write to and read from a file, open a file, and even take a relative path (if you feed it that) and resolve its absolute path with the .resolve() method. Its a nice tidy way to not have to import a bunch of ways of doing things and it makes your code look much cleaner! The ONLY thing I have had to adjust to was sometimes what you are using it with doesn't like that what you fed it was a path object. But that's alright because usually if you just wrap the path object in str() it will work fine!

Anyways, short story of a library I learned about that really was neat and I didn't realize I was missing. Figured this would be a cool place to maybe share and help some people with dealing with the nightmare that can be filesystem stuff!

21 Upvotes

15 comments sorted by

View all comments

4

u/N4v15 Mar 20 '19

Worth noting that pathlib (on bit bucket) is now in bugfix only mode and pathlib2 (installable via pip) has replaced/is replacing it.

The aim of pathlib2 is to support the entire stdlib which pathlib doesn't do.