Creating a Folder

00:00 Here I am in my Python REPL. I’m using IDLE, and I’m ready to tackle the first task. So the first task was I should create a new directory in my home folder that’s called my_folder/. And before I start tackling it, let’s take a look over into the home folder in the graphical user interface so that you see what it currently looks like, and also I will keep taking looks there once we do some changes to actually also see, you know, the feedback of what happens on my operating system when I run this Python code.

00:33 So this is my current home folder. You can see it’s sitting on MacBook Pro, Macintosh HD, Users, martin. So, I’m on a Mac, and this is what my home folder looks like at the moment. See, there’s just the standard folders in there and a Cool Secret Stuff folder that we will not talk about any further. Okay, but if I will create a directory, it should pop up here, and I should be able to see it also using the graphical user interface, because I’m actually creating a folder.

01:03 So let’s start by doing that in Python from the REPL and then head back here, and then actually see whether the folder shows up.

01:13 In order to do this, I will need the pathlib module, and I’m going to import the Path class from the pathlib module.

01:20 Let’s say from pathlib import Path. You could also just import pathlib, but most of the time, you’ll just be using the Path object, and it’s bit faster to write like that. Okay, so I need access to my home directory.

01:37 I’m going to define a variable that I’ll call home, and I will use Path.home() in order to let pathlib figure out what is my home directory. So this should work for you whether you’re on Linux, on macOS, or on Windows.

01:53 It should give you back your home directory. Here it is. It’s /Users/martin. And with, because it says PosixPath, you can see that I’m on a Unix system. All right, so I have access to my home directory.

02:07 Now what I want to do in there is to create a folder called my_folder/. All right, I will give that a variable too. I’m going to say my_folder is home and then "my_folder".

02:23 So that will be the path to my folder. Let’s double-check. How’s it going? Okay, so we have the path. It’s /Users/martin/my_folder. Now I also need to create it, and I can do that by saying my_folder.mkdir().

02:39 That stands for Make Directory. It’s a method that I need to call, so I put the parentheses, press Enter, and that should be it. Now, Python doesn’t give me any feedback whether or not this folder was created or not, and there’s ways I can check it with Python.

02:56 I can say my_folder.exists(), and it’s true. So we got a good chance that it’s actually there, but let’s check it out also with using the graphical user interface.

03:12 Heading back to my Finder here, I can see that now I have a folder called my_folder that sits at my home directory. Yippee! That worked out. Moving on to the next task.

Become a Member to join the conversation.