有没有更优雅的解决方案来修改这些文件名



我在";结束";的文件名,并希望能够通过函数对其进行更改。有三种不同的方式可以构建我正在接受的文件,这些方式包括在示例参数中。这最终使得处理不同的案件变得令人困惑。

我就是这样做的。它很有效,但看起来非常令人困惑。有比这更好的方法吗?更优雅但又不牺牲速度的东西?

import os
def change_index(file, index):
string_splits = os.path.basename(file).split("_")
new_string_splits = '_'.join(string_splits[:3]), '_'.join(string_splits[3:])
newer_string_splits = new_string_splits[1].split(".")
newest_string_splits = '.'.join(newer_string_splits[:1]), '.'.join(newer_string_splits[1:])
final_string = new_string_splits[0] + "_" + str(index) + "." + newest_string_splits[1]
print("before path", file)
print("after path ", os.path.join(os.path.dirname(file), final_string))
change_index("/Users/Name/Documents/untitled folder 3/Photos_Friends_20201201_0.jpg", 3)
change_index("/Users/Name/Documents/untitled folder 3/Photos_Friends_20191111_0.example_photo.jpg", 12)
change_index("/Users/Name/Documents/untitled folder 3/Photos_Friends_20210604_0.example_photo.jpg.something.expl", 2)

输出:

before path /Users/Name/Documents/untitled folder 3/Photos_Friends_20201201_0.jpg
after path  /Users/Name/Documents/untitled folder 3/Photos_Friends_20201201_3.jpg
before path /Users/Name/Documents/untitled folder 3/Photos_Friends_20191111_0.example_photo.jpg
after path  /Users/Name/Documents/untitled folder 3/Photos_Friends_20191111_12.example_photo.jpg
before path /Users/Name/Documents/untitled folder 3/Photos_Friends_20210604_0.example_photo.jpg.something.expl
after path  /Users/Name/Documents/untitled folder 3/Photos_Friends_20210604_2.example_photo.jpg.something.expl

由于之前总是有一个8位数的日期,因此您可以为使用正则表达式

import re
def change_index(file, index):
return re.sub(r"(d{8})_d", r"1_" + str(index), file)

更具体的

  • 如果要替换的编号始终是zero

    def change_index(file, index):
    return re.sub(r"(d{8})_0", r"1_" + str(index), file)
    
  • 日期部分的正则表达式稍微严格一些

    def change_index(file, index):
    return re.sub(r"([12][0-2]dd[0-1]d[0-3]d)_0", r"1_" + str(index), file)
    

最新更新