Home > Mobile >  How To Rename Files (Using Python OS Module)?
How To Rename Files (Using Python OS Module)?

Time:06-19

I have a folder which contains 100 songs named this way "Song Name, Singer Name" (e.g. Smooth Criminal, Michael Jackson). I'm trying to rename all the songs to "Song Name (Singer Name)" (e.g. Smooth Criminal (Michael Jackson)).

I tried this code. But, I didn't know what parameters to write.

import os

files = os.getcwd()

os.rename(files, "") # I'm confused because I don't know what to put here as parameters since I want to change only parts of the files' names, and not the files' names entirely.

Any suggestions on the parameters of "os.rename()"?

CodePudding user response:

Unlike the command line program rename which can rename a batch of files using a pattern in a single command, Python's os.rename() is a thin wrapper around the underlying rename syscall. It can thus rename a single file at a time.

Assuming all songs are stored in the same directory and ends with an extension like '.mp3', one approach is to loop over the return of os.listdir().

Additionally, it would be wise to check that current file is, indeed a file and not, say, a directory or symbolic link. This can be done using os.path.isfile()

Here is a full example:

import os 

TARGET_DIR = "/path/to/some/folder"

for filename in os.listdir(TARGET_DIR):
    # Only consider regular files
    if not os.path.isfile(filename):
        continue

    # Extract filename and extension
    basename, extension = os.path.splitext(filename)
    if ',' not in basename:
        continue # Ignore

    # Extract the song and singer names
    songname, singername = basename.split(',', 1) 

    # Build the new name, rename
    target_name = f'{songname} ({singername}){extension}'
    os.rename(
        os.path.join(TARGET_DIR, filename),
        os.path.join(TARGET_DIR, target_name)
    )

Note: If the songs are potentially stored in subfolders, os.walk() will be a better candidate than the lower level os.listdir()

CodePudding user response:

I would recommend you to write a loop using os.

However with pandas you can replace some Name snipeds with no problem, I would recommend chosing pandas for this Task!

  • Related