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

Filed Under: Python

Good day, learners! In this tutorial we are going to learn about Python Directory. In our previous tutorial, we learned about Python File.

Python Directory

Python Directory is basically working with operating system directories. To work with Python Directories, we need to import os module. This os modules contains functions to create, view, delete, rename directories.

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

  1. getcwd(): This function returns a string containing 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

Using these functions, you can do basic operation with python directories. But, to show you example, some sample code will be given to help you understand about the implementation.

Getting List of Directories

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/imtiaz/directory.py ==================
/home/imtiaz
['locale', 'sbin', 'local', 'games', 'lib', 'share', 'lib32', 'src', 'include', 'bin']
>>> 

Which is same as the actual picture.

python directory, python create directory

Getting The Location of Current Directory

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/imtiaz/cur_dir.py ==================
/home/imtiaz
>>>

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

Why Do We Need Python Directories

Reading this tutorial, it may come to your mind that why we need Python Directories. In this section we will going to discuss this thing.

Suppose, you are making some a 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 a file or read a file from that directory. To do so, Python has introduced this facility. You may not need this now, but Python Directory may help you later.

Python Create Rename Delete Directory Example

A simple program showing how to create directory, then rename and delete it.


import os

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

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

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

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

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

#delete non-empty directory
os.rmdir("test")
print(os.listdir(os.getcwd()))

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


pankaj:BasicPython pankaj$ python directory.py 
/Users/pankaj/temp
['data', 'test']
['data1', 'test']
['test']
Traceback (most recent call last):
  File "directory.py", line 22, in <module>
    os.rmdir("test")
OSError: [Errno 66] Directory not empty: 'test'

Notice that os.rmdir can only remove empty directory. So to delete a non-empty directory, we will have to use shutil module. Below is a simple program to delete directory using shutil module.


import shutil

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

So that’s all for python directory tutorial. Hope that you have learned well. Try to implement functions that are not implemented here. That’s you task! If you face any problem regarding this, feel free to use the comment section.

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
Search in posts
Search in pages