有没有一种方法可以使用用户输入批量重命名文件夹中的文件?

时间:2019-05-08 03:17:53

标签: python python-3.x rename file-rename

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

每隔几个月我都会得到相同的工作,重命名数百张照片。我花了数小时甚至数天的时间。到目前为止,我有代码询问测试的类型(照片正在捕获),测试的编号,从用户输入进行的测试的深度。

但是我遇到了麻烦,我希望能够批量重命名,但是不同的照片显示的深度不同。例如,我希望这些照片成为名称: 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等)的顺序排列。

1 个答案:

答案 0 :(得分:3)

我在这里做一些假设:

  • 文件夹的名称是钻孔的名称
  • 每个钻孔的文件名可能会有所不同,但是按字母数字排序时,第一个将是最靠近地面的文件名
  • 所有集合需要增加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.jpg之类的名称而不是BH01_0-5.jpg,因为它们的排序会更好。

请注意,该脚本仅显示其功能,您只需注释掉print语句并删除move语句前面的注释符号,它实际上就会重命名文件。

相关问题