如何使用现有名称的一部分重命名 Python 中的多个文件?

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

我在一个目录中有几百个 .mp4 文件。最初创建时,它们的名称被设置为 "ExampleEventName - Day 1"、"ExampleEventName - Day 2" 等,因此它们不是按时间顺序排列的。

我需要一个脚本来修改它们的每个名称,方法是将相应字符串中的最后 5 个字符添加到名称的前面,以便文件资源管理器正确排列它们。

我尝试在 for 循环中使用 os 模块的 .listdir() 和 .rename() 函数。根据我的输入,我得到 FileNotFoundError 或 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

您遇到了多个问题: 您正在尝试增加不应增加的值。此外,您还创建了列表 file_list,因此它不应再接受任何参数。

使用语法时:

for x in y: 

您不必增加该值。它会简单地遍历列表,直到没有剩余的为止。

因此,您只需省略增量并遍历列表 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

现在您的解决方案应该可以工作了。

其他一些方法: 不基于基础长度(子名称为 5)

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)