Creating Path Objects From Strings
You do that by typing
import pathlib. And I will head over to an IDLE session to work alongside the things that I’ll be talking about here. In the IDLE REPL, I’m start off by typing
import pathlib, and it gives me access to the
pathlib module. Now what do you do with the
You can pass just directly a string in there that represents the file path, you can use
Path.cwd(), which stands for current working directory, or you can use the
/ (forward slash) operator as well as another class method called
joinpath(), which is equivalent to using the
I’m here on a macOS operating system. Let’s say I want to represent a path that looks like that, so it goes
/Users/Martin/, which is my username on this computer, then on to the
Desktop/ and finally a file called
This is the path I want to represent. Now, the quickest way to create a
Path object for this path is to pass in this value as a string.
pathlib.path … and then I create a string, paste what I wrote up there in the comment, close the parentheses, and press Enter.
And the reason for that is that I am on a macOS operating system. That is a Unix-based system, like also Linux systems are. This is why it says
PosixPath. If you were on a Windows computer, you’d get something like
WindowsPath prepended to all of the paths that you create on that system. Otherwise, it looks pretty similar. However, if you are on a Windows system, then you might run into a problem.
Windows paths use
\ characters instead of
/ characters to represent paths, and the
\ character in Python has a special meaning because it starts an escape sequence, which means that if you pass just a plain string with a
\, then Python is going to not interpret the
\ character as a
\ character but thinks that you want to start an escape sequence.
This will break your Windows paths if you don’t account for it, and you’ll get syntax errors. There are two ways around it. You can either use a
/ instead, which means you can just represent a Windows path with the normal
C:, but and then instead of using a
\ like you normally would, you just use a
Another way of doing it is to use raw string, and you can do that in Python by prefixing the string with just the
r character, so you put this
r in front of the string, and then you can use
\ characters like you would normally with a Windows path.
Become a Member to join the conversation.