Search code examples
pythonfile-renameshutilpython-os

How do I rename multiple files in Python, using part of the existing name?


I have a few hundred .mp4 files in a directory. When originally created their names were set as "ExampleEventName - Day 1", "ExampleEventName - Day 2" etc. thus they are not in chronological order.

I need a script to modify each of their names by taking the last 5 characters in the corresponding string and add it to the front of the name so that File Explorer will arrange them properly.

I tried using the os module .listdir() and .rename() functions, inside a for loop. Depending on my input I get either a FileNotFoundError or a TypeError:List object is not callable.


    import os
    os.chdir("E:\\New folder(3)\\New folder\\New folder")


    for i in os.listdir("E:\\New folder(3)\\New folder\\New folder"):
        os.rename(i, i[:5] +i)

Traceback (most recent call last):
  File "C:/Python Projects/Alex_I/venv/Alex_OS.py", line 15, in <module>
    os.rename(path + i, path + i[:6] +i)
FileNotFoundError: [WinError 2] The system cannot find the file specified:

    import os, shutil

    file_list = os.listdir("E:\\New folder(3)\\New folder\\New folder")

    for file_name in file_list("E:\\New folder(3)\\New folder\\New folder"):
        dst = "!@" + " " + str(file_name) #!@ meant as an experiment
        src = "E:\\New folder(3)\\New folder\\New folder" + file_name
        dst = "E:\\New folder(3)\\New folder\\New folder" + file_name

        os.rename(src, dst)
        file_name +=1

Traceback (most recent call last):
  File "C:/Python Projects/Alex_I/venv/Alex_OS.py", line 14, in <module>
    for file_name in file_list("E:\\New folder(3)\\New folder\\New folder"):
TypeError: 'list' object is not callable

Solution

  • Some other approach: Not based on based length ( 5 for subname )

    import glob
    import os
    
    # For testing i created 99 files -> asume last 5 chars but this is wrong if you have more files
    # for i in range(1, 99):
    #     with open("mymusic/ExampleEventName - Day {}.mp4".format(i), "w+") as f:
    #         f.flush()
    
    # acording to this i will split the name at - "- Day X"
    
    files = sorted(glob.glob("mymusic/*"))
    
    for mp4 in files:
        # split path from file and return head ( path ), tail ( filename )
        head, tail = os.path.split(mp4)
        basename, ext = os.path.splitext(tail)
        print(head, tail, basename)
        num = [int(s) for s in basename.split() if s.isdigit()][0] #get the number extracted
        newfile = "{}\\{}{}{}".format(head, num, basename.rsplit("-")[0][:-1], ext) # remove - day x and build filename 
        print(newfile) 
        os.rename(mp4, newfile)