This Tutorial we will see how to create or delete a Directory in Python so we will focus on answer several questions, also, a few practical examples to show you how these methods work.
One of the most used and important modules is the OS Module, this module belongs to the core part of the Python ecosystem, it is very important because the manipulation of an directory or a folder is very crucial to any Software Developer or Data Scientist.
How to import the OS Module
Firstly use the file system functions (suchlike creating or deleting directories) we need to employ a separate module, and for that we need to import the OS module in the first place.
The OS Module contains all the methods that we are going to use in this tutorial.
Managing the Working Directory in Python
Usually all the Programs executed on our computers has a current working directory.
The files or folders that do not start with the root folder are assumed to be on the current working directory, however, we have two different ways to specify a path.
The Absolute Paths are all the Paths that starts with the root folder like for example:
The Relative Paths are all the Paths that are relative to the program’s current working directory, for instance let’s assume that the path C:\BigdataCracker is our Working directory:
Notice that we use one Dot as shortcut for the Working Directory and Double Dots for the “Parent Folder” of the Working directory.
How to know my Working Directory in Python
So, how can we know whats our Current Directory? Well that’s fairly easy!
Any way, you can find changing the current directory fairly similar to the same way as the UNIX
After importing the OS Module all we need to do is to use the getcwd method, we can save it into a variable or print it on the command prompt.
print("My Working Directory is: " + os.getcwd())
By Printing the method getcwd we get the path of our working directory
How to Change my Working Directory
To change the Current Working Directory is pretty simple, we only need to use the method chdir and passing by argument the new path we want to assing as the new Working Directory.
When defining a new Working Directory we can use the Absolute Path or the Relative.
Changing my Working Directory using Absolute Path
When using an Absolute path remember the slash \ character can be a escape character however by placing the letter r before the string we are telling Python that the following string is a raw string.
Another way to tell python to change the Working Directory without passing a raw string is by escaping the slash itself.
Tip: This examples only Work on Windows, for OS X or Linux you need to use the Backward Slash / like:
Managing Directories in Python
Creating a Directory also needs to keep in mind if we are using an Absolute or a Relative path.
How to Create a New Directory
Again the OS Module as the perfect method to create a new folder in Python, mkdir function and pass the new directory path to be created as argument to the function.
Creating the folder Code in Absolute Path would be like:
Assuming that our Working Directory is “C:\BigDataCracker“, creating the folder “Code” in Relative Path would be.
We need always to understand that creating a folder can be “relative” to the Working Directory.
Don’t worry if the
FileExistsError exception is raised, in other words, it only means that it wasn’t possible to create the folder because it already exists, so we don’t need to create a new folder.
try: os.mkdir('Code') except OSError as error: print(error)
The previous snippet of code will Try to execute the code by creating the Folder “Code” in case of error the message will be printed to the screen by using the Print Function and the program will not exit because of that error.
Creating multiple directories in Python
Sometimes we may need to create several Sub-folders, on the previous Python example we can do that but we need to create folder by folder.
Furthermore the method makedirs creates all the folders, including sub-folders to ensure that the full Path exists.
In the Previous example notice that Not only the “Examples” Folder is created but also the Parent folder “Others”.
How to Delete a Directory in python
However, deleting a folder is the goal for rmdir function, by passing the path directory as argument to the function.
When deleting a folder we need to ensure that the folder is empty or the
FileExistsError exception is raised.
Removing the folder in Absolute Path would be like:
Assuming that our Working Directory is “C:\BigDataCracker“, deleting the folder “Code” in Relative Path would be.
Again, we can treat the
FileExistsError exception, this only means that the folder we want to delete cannot be deleted or because it doesn’t exist or it is not empty.
try: os.rmdir('Code') except OSError as error: print(error)
Deleting multiple directories
Sometimes we may need to delete a whole brache, on the previous example we aren’t able to delete several folders at the same time, anyhow, Python has a great function for these cases.
With removedirs method all the folders are deleted including sub–folders necessary to ensure that the full Path is deleted.
Remember that you need to ensure that every folder on the path provided doesn’t have any file inside, i.e. all the folders must be empty or the
FileExistsError exception is raised.