python - 有没有办法可以通过用户输入批量重命名文件夹中的文件?
问题描述
希望让用户输入重命名批处理照片文件,但更改结束后缀。
每隔几个月,我就会得到相同的工作,重命名数百张照片。如果不是几天的话,我需要几个小时才能完成。到目前为止,我有代码询问测试的类型(照片正在捕捉)、测试的数量、测试从用户输入到用户输入的深度。
但我遇到了一个障碍,我希望能够批量重命名,但不同的照片显示不同的深度。因此,例如,我希望照片命名为: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 等)使后缀连续。
解决方案
我在这里做一些假设:
- 文件夹的名字就是钻孔的名字
- 每个钻孔的文件名可能不同,但按字母数字排序时,第一个将是最接近地表的文件名
- 所有套装都需要 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
它实际上会重命名文件。
推荐阅读
- regex - 使用记事本++上的正则表达式提取以不同值重复的标签
- javascript - 追加限制为 1 时更新变量的值
- php - PHP - 对不同的数组求和
- tomcat - intellij 的 gwh 问题:无法反序列化响应
- c++ - 有没有办法在条件语句中声明对象?
- r - 多列时间序列分析
- angular - 如果我决定在没有 ngx-leaflet 库的情况下在 Angular 中使用传单,我需要照顾自己什么?
- python - 如何比较两个列表的效率
- html - Recharts - 将 dataKey 的值传递给子组件
- python - 如何使用 Pandas 从 Python 中的 Url 读取数据?