首页 > 解决方案 > 有没有办法可以通过用户输入批量重命名文件夹中的文件?

问题描述

希望让用户输入重命名批处理照片文件,但更改结束后缀。

每隔几个月,我就会得到相同的工作,重命名数百张照片。如果不是几天的话,我需要几个小时才能完成。到目前为止,我有代码询问测试的类型(照片正在捕捉)、测试的数量、测试从用户输入到用户输入的深度。

但我遇到了一个障碍,我希望能够批量重命名,但不同的照片显示不同的深度。因此,例如,我希望照片命名为:BH01_0-5m,然后命名下一张照片。BH01_5-10m

但我只知道如何编码,所以一切都被命名为 BH01_0-5m

这是我到目前为止用于用户输入的代码:

borehole = raw_input("What type of geotechnical investigation?")
type(borehole)

number = raw_input("What number is this test?")
type(number)

frommetre = raw_input("From what depth (in metres)?")
type(frommetre)

tometre = raw_input("What is the bottom depth(in metres)?")
type(tometre)

name = (borehole+number+"_"+frommetre+"-"+tometre)
print(name)

我得到了我想要的第一个照片文件的标题,但是如果我在每个文件夹中有 4 张照片,它们现在将被重命名为与用户输入完全相同的内容。我希望以 5 米为单位(0-5、5-10、10-15、15-20、20-25 等)使后缀连续。

标签: pythonpython-3.xrenamefile-rename

解决方案


我在这里做一些假设:

  • 文件夹的名字就是钻孔的名字
  • 每个钻孔的文件名可能不同,但按字母数字排序时,第一个将是最接近地表的文件名
  • 所有套装都需要 5 米的增量

您要执行的操作可以在两个嵌套循环中完成:

  • 对于所有文件夹:
  • 对于每个文件夹中的所有文件:
  • 重命名文件以按顺序匹配文件夹名称和一些深度

这是一个例子:

from pathlib import Path
from shutil import move

root_folder = 'c:\\temp'
for folder in Path(root_folder).iterdir():
    if folder.is_dir():
        startDepth = 0
        step = 5
        for file in Path(folder).iterdir():
            if file.is_file():
                new_name = f'{folder.name}_{str(startDepth).zfill(3)}-{str(startDepth + step).zfill(3)}{file.suffix}'
                print(f'would rename {str(file)} to {str(file.parent / Path(new_name))}')
                # move(str(file), str(file.parent / Path(new_name)))
                startDepth += step

请注意,我还添加.zfill(3)了每个深度,因为我认为您会更喜欢类似的名称BH01_000-005.jpgBH01_0-5.jpg因为它们会更好地排序。

请注意,此脚本仅打印它将执行的操作,您可以简单地注释掉print语句并删除语句前面的注释符号,move它实际上会重命名文件。


推荐阅读