我在文件名的“末尾”有一个索引,并希望能够通过函数更改它。我在示例参数中包含的文件可以通过三种不同的方式构建。这最终使处理不同的情况变得混乱。
这就是我最终这样做的方式。它有效,但看起来非常令人困惑。还有比这更好的方法吗?更优雅但不牺牲速度的东西?
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]\d\d[0-1]\d[0-3]\d)_0", r"\1_" + str(index), file)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句