Staying Lenient
00:00 So the script ran and did what it was supposed to do. But what happens if I run this script again? So let me press F5 once more, and on the second run, now I get an error.
00:11
It tells me FileExistsError
, that the images/
directory already exists. So this is where I can use a one of the keyword parameters to .mkdir()
, and I can say exist_ok=True
,
00:26
which just means that Python’s not going to throw this FileExistsError
if the directory already exists, which you might want that or not, depends because maybe you only want to run this script successfully if the images/
directory doesn’t exist yet.
00:42
But I think for the use case that we have here—that I want to create this new folder, images/
, and move all the image files in there—the main point isn’t really to create the images/
directory, right?
00:51
I just want to move the image files there. So if there already is an images/
directory, I’m okay with that. I can also imagine that I’m going to want to run this script more often than just once because maybe I agglomerate some more screenshots or images in the subfolders, and I’m just going to want to be able to always move these into the images/
directory by running my script, so I can anticipate that this images/
directory is already going to exist, and I’m going to run the script more often. So in this case, it seems like a good idea to be okay with it if it already exists. Okay, let’s test that out and run it again. F5. All right, and IDLE tells me I need to save the file first before I can run it.
01:32
I’m okay with that. All right, and looks like my words got me again. It’s not actually called exists_ok
. I got another error here that unexpected argument exists_ok
. This is something that I run into often.
01:49
It’s actually called exist_ok
. I keep messing this up, but luckily Python just tells me if something is wrong, and I know it’s either exist_ok
or exists_ok
. So if I got it wrong, then I just try to run it again. After removing the s
, save the file, and now it works. Now, Python isn’t complaining, not because the directory already exists and also not because I used the wrong name for the keyword parameter. All right, so images_dir.mkdir(exist_ok=True)
. Keep in mind, running into some sort of errors is never a problem.
02:26
You’re just cooperating here with Python. Python is telling you didn’t understand something that you want to say, and then you, yeah, go ahead. And if you don’t know what went wrong here, you might just go ahead to the documentation again and look up what keyword parameters does .mkdir()
take, and then you’ll see, okay, it’s exist_ok
without the s
in there. Awesome. So that’s an improvement to before.
02:48 I’m going to be able to run this script multiple times and, like, just keep moving images into this image folder. And that’s what we’re going to tackle next.
02:57 Then we want to move all the image files to that folder.
Become a Member to join the conversation.