如何使用 python 重命名文件夹中的多个文件?

How does one rename multiple files within folders using python?

我在 'my documents' 中有 1000 多个文件夹。每个文件夹中只有4张照片需要依次命名为'North' 'East' 'South'和'West'。目前它们被命名为 DSC_XXXX。我写了这个脚本,但它没有执行。

import sys, os

folder_list = []
old_file_list = []
newnames = [North, South, East, West]

for file in os.listdir(sys.argv[1]):
    folder_list.append(file)

 for i in range(len(folder_list)):
    file = open(folder_list[i], r+)
    for file in os.listdir(sys.argv[1] + '/' folder_list[i]):
       old_file_list.append(file)
       os.rename(old_file_list, newnames[i])

我的思路是把这1000个文件夹的名字全部取出来存到folder_list里。然后打开每个文件夹,将4个图片名称保存在old_file_list中。从那里我想使用 os.rename(old_file_list, newnames[i]) 将 4 张照片重命名为 North East South 和 West。然后我希望它循环遍历 'my documents' 中的尽可能多的文件夹。我是 python 的新手,如有任何帮助或建议,我们将不胜感激。

您不需要所有列表,只需即时重命名所有文件即可。

import sys, os, glob

newnames = ["North", "South", "East", "West"]

for folder_name in glob.glob(sys.argv[1]):
    for new_name, old_name in zip(newnames, sorted(os.listdir(folder_name))):
       os.rename(os.path.join(folder_name, old_name), os.path.join(folder_name, new_name))

下面是我将如何使用 antipathy [1]:

# untested

from antipathy import Path

def check_folder(folder):
    "returns four file names sorted alphebetically, or None if file names do not match criteria"
    found = folder.listdir()
    if len(found) != 4:
        return None
    elif not all(fn.startswith('DSC_') for fn in found):
        return None
    else:
        return sorted(found)

def rename(folder, files):
    "rename the four files from DSC_* to North East South West, keeping the extension"
    for old, new in zip(files, ('North', 'East', 'South', 'West')):
        new += old.ext
        folder.rename(old, new)

if __name__ == '__main__':
    for name in Path.listdir(sys.argv[1]):
        if not name.isdir():
            continue
        files = check_folder(name)
        if files is None:
            continue
        rename(name, files)

[1] 免责声明:antipathy 是我的项目之一