Search code examples
pythonpython-3.xfileextension-methods

How to *not* change the file extension while changing a filename?


I'm trying to remove the numbers from the file name. But in doing so it also removes the extension and the mp4 file turns into a mp. What is a good solution to solve this?

import os

def file_rename():
    name_list=os.listdir(r"C:\Users\caspe\OneDrive\Documents\Övrigt\Kodning\Twitch")
    print(name_list)
    saved_path=os.getcwd()
    print("Current working directory is"+saved_path)
    os.chdir(r"C:\Users\caspe\OneDrive\Documents\Övrigt\Kodning\Twitch")

    for file_name in name_list:
        print("old name"+file_name)
        print("new name"+file_name.strip("0123456789"))
        os.rename(file_name, file_name.translate(str.maketrans('','','0123456789-')))
    os.chdir(saved_path)

file_rename()

Solution

  • You can use pathlib.Path objects. It has name and suffix attributes, and a rename method:

    import re
    from pathlib import Path
    for file in Path(r'C:\tmp').glob('*'):
        if not file.is_file():
            continue
        new_name = re.sub('\d','', file.stem) + file.suffix
        file.rename(file.parent/new_name)
    

    The parent attribute gives the folder the file belongs to and the is_file method is used to check that we are handing a regular file (and not a folder). New Path objects are created easily with the / operator (full new filepath is file.parent / new_name).

    The re.sub() is used to replace the numbers (\d means a digit) in the old filename stem part.