Python Directory Operations – Create, Rename, Delete, Listing, Change

Filed Under: Python

Good day, learners! In this tutorial, we are going to learn about Python Directory operations. We’ll discuss more on how to create directories, rename directories using the Python os.rename() method, deleting and changing directories and more.

In our previous tutorial, we learned about Python File Operations.

Examples of Python Directory Operations

Let’s go over the different directory operations in Python. To begin working with a file, you need to change the directory to the path where we have the files and folders placed. So let’s begin with changing the directory to our working path.

1. Getting List of Directories – os.listdir()

You can get the list of directories on a specific location. To do so, you have to to use listdir(location) function. If you put the location, the function will return a list of string containing the names of the directories of the given location. The following code will help you understand the thing

import os #the os module need to be imported

print(os.listdir('/usr')) #here the location is ‘/usr’

The output of the following code will be:

================== RESTART: /home/pankaj/directory.py ==================
/home/pankaj
['locale', 'sbin', 'local', 'games', 'lib', 'share', 'lib32', 'src', 'include', 'bin']
>>>

Which is same as the actual picture.

python directory, python create directory

2. Getting The Current Directory – os.getwd()

As we said earlier, you can get the location of the current directory you’re in by using getcwd() function. The following code will illustrate you the idea

import os #we need to import this module

print(os.getcwd()) #print the current location

The output of the following code will be

================== RESTART: /home/pankaj/cur_dir.py ==================
/home/pankaj
>>>

Similarly, you can implement all those functions that are mentioned above. Try those, give yourself a challenge!

3. Change Directory – os.chdir()

To do that, we first import the os module and then begin with using the os.chdir() method to change the base path of our program.

import os

#change directory
os.chdir('/Users/pankaj/temp')

#print current working directory
print(os.getcwd())

4. Create Directories – os.mkdir()

To create a directory, we need to use the os.mkdir() method. Let’s create a directory named “data”. We’ll then print the list of directories within the path with the os.listdir() method.

#create directory
os.mkdir("data")
print(os.listdir(os.getcwd()))

5. Rename Directories – os.rename()

Let’s rename the data directory that we created. We’ll change the name to data1 using the Python os.rename() method.

#rename directory
os.rename("data","data1")
print(os.listdir(os.getcwd()))

6. Delete a directory – os.rmdir()

Now that we have created the data directory and renamed it to data1, let’s delete the directory. We can delete folders using the Python os.rmdir() method.

#delete directory
os.rmdir("data1")
print(os.listdir(os.getcwd())

When we execute above program through terminal, it produces following output.

NOTE: os.rmdir can only remove an empty directory.

So to delete a non-empty directory, we will have to use shutil module. Below is a simple program to delete the directory using the shutil module.

import shutil
shutil.rmtree('/Users/pankaj/temp/test')

Now let’s go over some of the theory of what directories are how to work with directories

Summary of Python Directory Operations

Basically, there are some common functions to access Python Directories. The functions are given below

  1. getcwd(): This function returns a string containing the current directory from where to code is being executed.
  2. listdir(location): This function returns a list string containing current the names of current directories.
  3. chdir(location): This function changes the current directory to the given location
  4. mkdir(name): This function creates a new directory labeling with the given name.
  5. rename(old_name,new_name): This function renames the old_name directory to new_name directory

Why do we need to work with directories in Python?

Reading this tutorial, you may wonder “Why would you need to work with directories within your Python app?

Consider this situation:

Suppose, you are making some software using Python where you need to read/write files from different directories. The directories can be dynamic so that you cannot fix the directory from your code, rather you need to choose the directory dynamically.

After choosing the directory, you may have to create a new directory or write to a file or read from a file from that directory.

To do so, Python has introduced this facility.

That’s all for this tutorial. Hope you’ve learned the Python directory operations well and know exactly how to create directories, rename directories, move and play around with the directories using Python.

Reference: https://docs.python.org/3.6/library/shutil.html#shutil.rmtree

Comments

  1. Anand Patil says:

    Sir,There are some files in a folder.I want to rename all files in a folder. The files name in folder also exists in the excel sheet. I mean to say the file name to be renamed exists in a excel sheet. How do i do it??? Kindly reply i am Mech Engg still learning python.Kindly help please.

  2. bryankho says:

    Hi, may i know how to insert box.value (which is from GUI) into a specific directory? Initially, i created a folder named “new_folder” at a specific directory such as ‘/Main app/new_folder/’ by using python in Raspberry Pi 3. After that i successfully rename the original folder name to a new name. But i encountered problem on save images into the new folder such as below coding:

    os.mkdir(‘new_folder’) #try make new folder during start store new faces
    os.rename(new_folder, box.value) #change folder name(oldname, newname)

    path = ‘./human_faces/box.value/’ + str(face_count) + ‘.jpg’

    What should i do?

    1. Pankaj says:

      First of all, check where your program is trying to write the file? Sometimes, a relative path causes an issue if the base path is set to somewhere else.

      Secondly, check if it’s directory permission issue?

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content