0

I have one scenario where i have to rename the files in the folder. Please find the scenario,

Example :

Elements(Main Folder)<br/>
    2(subfolder-1) <br/>
       sample_2_description.txt(filename1)<br/>
       sample_2_video.avi(filename2)<br/>
    3(subfolder2)
       sample_3_tag.jpg(filename1)<br/>
       sample_3_analysis.GIF(filename2)<br/>
       sample_3_word.docx(filename3)<br/>

I want to modify the names of the files as,

Elements(Main Folder)<br/>
    2(subfolder1)<br/>
       description.txt(filename1)<br/>
       video.avi(filename2)<br/>
    3(subfolder2)
       tag.jpg(filename1)<br/>
       analysis.GIF(filename2)<br/>
       word.docx(filename3)<br/>

Could anyone guide on how to write the code?

Rider_BY
  • 1,129
  • 1
  • 13
  • 31
Aishwarya
  • 3
  • 2

2 Answers2

0

Recursive directory traversal to rename a file can be based on this answer. All we are required to do is to replace the file name instead of the extension in the accepted answer.

Here is one way - split the file name by _ and use the last index of the split list as the new name


import os
import sys

directory = os.path.dirname(os.path.realpath("/path/to/parent/folder")) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
    for filename in files:
        subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
        filePath = os.path.join(subdirectoryPath, filename) #get the path to your file
        newFilePath = filePath.split("_")[-1] #create the new name by splitting the old name by _ and grabbing last index
        os.rename(filePath, newFilePath) #rename your file

Hope this helps.

S.Au.Ra.B.H
  • 457
  • 5
  • 9
  • Thank you for the suggestion. I have tried to execute the code and customized the code. I am getting the error like this "FileNotFoundError: [WinError 2] The system cannot find the file specified: 'BUG_10_ALM_snapshot_5.jpg' -> 'ALM_snapshot_5.jpg'" I am having the respective file in that particular folder but getting this error. Could you please help.@saurjog – Aishwarya Feb 25 '20 at 17:31
  • @Aishwarya could you elaborate? What is the structure of the directory? – S.Au.Ra.B.H Feb 27 '20 at 00:35
-1

check below code example for the first filename1, replace path with the actual path of the file:

import os

os.rename(r'path\\sample_2_description.txt',r'path\\description.txt')
print("File Renamed!")
  • Thank you for the suggestion.The code which you have mentioned has for the single files or we can use the above method for changing 5 to 10 files names.But I am having above 1000 files which are to be renamed. – Aishwarya Feb 13 '20 at 09:06