Moving a File
In this lesson, you will learn how you can move files and folders using Python’s
pathlib module. Now, if you consider the folder structure that you’ve worked with so far, it’s kind of not that nicely structured and not really ideal. So you have, for example,
goals3.txt that sits inside of the
plans/ directory, but you have
goals2 out here directly in the
So what you want to do in this lesson is you’re going to move the
yearly/ directory inside of the
plans/ directory, and you’re also going to move
goals3.txt out of the
plans/ directory and directly into the
To move files and folders using
pathlib, you can work with the
.replace() method. And the
.replace() method, you call it on a
Path object that is your source path, and you pass it an argument that is going to be your destination path. So for this, I will have to build two paths.
So I want to say the
old_path_goals_3—let’s be very explicit here—is inside of the
"notes" directory and then inside of the subdirectory called
"plans", and then we have the filename that was
So you can see the new path. Whoops.
new_path_goals_3 is going to be
notes/ and then directly
goals3.txt. And now I can use the
.replace() method to move it from one path to the new path. I’m going to say
old_path_goals_three.replace() and then pass it the target. So, this is the new path
goals3. And once I execute this, you can see that I get as a return value, I get the new path of where I moved the file to in this case. And now just to double-check that, I’m going to use
.iterdir() just to see what’s inside of
Keep in mind that if the new path already existed—so, if we already had a file called
goals3.txt directly in the
notes/ directory—then using
.replace() would actually replace the new path with the old path.
Become a Member to join the conversation.