Renaming Folders using Python

We will write a python code rename folders. This is one of the python i/o content.

Directory Tree:

Let's create the following directory. Everything needs to be in the same directory.

folder-tree

Printout all directory files AND folders:


Let's first import the library os Python library and Print out all the files in our current directory:



  import os

  #Print all files and folders in the searchText.py directory
  print(os.listdir())
        

The output should look similar to this showing 4 file names:


Output:

['Folder1', 'Folder2', 'RenameFolder.py']

Taking Target Folder name and new name from User:


Now we going to write two lines of code that will take two input from the user to do the following:

  • Taking user input, which will specify the folder we want to rename.
  • Taking user input , which will specify the new Folder name.


  which_file = input("Enter the fiile name you want to change:")
  rename_file_name = input("Enter the new name you want :")
                

Testing and verifying that the folder was renamed :


We can simply verify that the folder is renamed by calling os.listdir() and see if the name of our folder has changed

The output should look as folows, where here we are trying to rename Folder1 to RenamedFolder.

['Folder1', 'Folder2', 'RenameFolder.py']]

Enter the fiile name you want to change:Folder1

Enter the new name you want :RenamedFolder

['Folder2', 'RenamedFolder', 'RenameFolder.py']