简体   繁体   中英

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

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)

You're having multiple problems: You're trying to increment a value that should not be incremented. Also you've created the list file_list, and thus it should not take any arguments anymore.

When using the syntax:

for x in y: 

you do not have to increment the value. It will simply iterate through the list until there is no more left.

Therefore you simply have to leave out the incrementation and iterate through the list file_list.

import os, shutil

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

for file_name in file_list: #removed the argument, the as file_list is a list and thus not callable.
    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 removed this line

Now your solution should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM