Using the Forward Slash Operator
The third way to create a
Path object is using the
/ operator. And I can do something like typing
pathlib.Path.home() and then concatenate another string by just using this operator that is a
/ and then followed up by a string, and you can continue doing this basically forever, as many pieces of the path you want to add. And in this example, so if you concatenate
"Desktop" and then, again with the
/ operator, the string
"hello.txt", then again you get this
Path object with the value that you’ve seen before,
and that creates another
Path object with the same value that you’ve seen before. Now, the interesting thing about this is that it’s an operator just like the
+ (plus) in
2 + 2 in Python is an operator, but it is specific to
I need to first create a
Path object. I do this using
.home(), as you’ve seen earlier. And then instead of using the
/ character, I can also say
.joinpath() and then pass in the string here
So whatever you consider as the most readable for you, you can use here. Remember that the
/ is a shortcut for the
.joinpath() method and that you can either chain multiple
/ operators or also
.joinpath() methods with single pieces of the path that you want to create, or you can just add a path string on the right side of this operator as well.
The important thing here is that this is only going to work if we have at least one
Path object part of the operation, which here you created by using the
.home() class method that we discussed in the previous lesson. Okay, let’s quickly sum this up.
You’ve now seen three different ways of creating
Path objects. The first one was from a string where, keep in mind, with Windows, you’ll have to do a little extra, either using forward slashes or using raw strings.
Become a Member to join the conversation.