Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Writing Code to Move Files

00:00 Okay, so that worked nicely. Let’s bring this functionality over into the script. For that, I’m just going to go ahead and copy what I wrote here—it was working well, after all—and I’m going to paste it here into the script.

00:14 Now, maybe let’s actually look at the names of the files, not just the suffix, and see whether this still works. So it’s going to look into copy_dir/ and look for these three file types and print out the name of the files. So I will go ahead and press F5

00:34 and seems to be still working nicely. So I get image1, 3, 2, and 4, all of the images that I want to move.

00:42 And that’s the next step. Now, instead of just printing out their names, I want to move them. You learned about the .replace() method that you can use on a Path object to move it from a source to a destination. I do have access to the source here, so this path is going to be the path of the four files that I want to move.

01:01 And now I also need a destination. So I have source of file to move and then I also need the destination. How do I get the destination? I already know that I want to put them inside of the images/ folder, and I have access to that path, or just the images_dir.

01:20 So I just need to add the name of the file to images_dir, basically. And as you just saw before, you can get access to the name of the file by saying path.name.

01:33 Let’s do it. Source. Okay. Well, actually move files.

01:40 So I will say source is going to be the path, and I want to replace it with the destination, and the destination is going to be inside of images_dir,

01:53 and then the filename—I’m going to keep the same filename, so I will say path.name.

02:03 Okay, can get rid of the print() function here. Here we are. path.replace(images_dir / path.name). Okay, so now when I run this script, it is going to change the file structure of my copy_dir/.

02:17 This is the one I’m running it on at the moment because I’m still in testing mode, so to say. And let’s give it a go and check for the results in the next lesson.

Become a Member to join the conversation.