Creating a Folder
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.
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.
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.
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.
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.
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
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.
Become a Member to join the conversation.