Search code examples
pythondirectoryrenamesubdirectory

mp3 file name replace


So my concern on a logic of a program. I have a Music folder with many mp3 files with underscores in names (MC_-_Best_track.mp3). So I want to scan this folder and replace all underscores with whitespaces.

I want to write it myself first but I need a kickstart for that) Can you help me in logic?

Update:

Still struggle with subfolders.

{

import os 
path = r"C:\Users\mugger\Desktop\Music fo Python"

for folders, subfolders, files in os.walk(path):
    for subfolders in folders:
        for file in files:
            if file.endswith(".mp3"):
                os.rename(os.path.join(path, file), 
                os.path.join(path, file.replace("_"," ")))

}

If I set path directly I get only one file renamed and getting error:

FileNotFoundError Traceback (most recent call last) c:\Users\mugger\Desktop\programming\Udemy\0149. List of Possible Widgets.ipynb Cell 2 in <cell line: 6>() 8 for file in files: 9 if file.endswith(".mp3"): ---> 10 os.rename(os.path.join(path, file), os.path.join(path, file.replace("_"," ")))

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\Users\mugger\Desktop\Music fo Python\old\Queen - Under_Pressure.mp3' -> 'C:\Users\mugger\Desktop\Music fo Python\old\Queen - Under Pressure.mp3'


Solution

  • I think this maybe work

    import os 
    
    path = "your folder path"
    
    
    data = os.listdir(path)
    
    
    for  file in data:
        if file.endswith(".mp3"):
    
    
        file_name = file.lower()
        file = file_name
        
    
            os.rename(os.path.join(path, file), os.path.join(path, file.replace("_"," ")))