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

弗里奥

我在文件名的“末尾”有一个索引,并希望能够通过函数更改它。我在示例参数中包含的文件可以通过三种不同的方式构建。这最终使处理不同的情况变得混乱。

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

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

是否有一种更优雅的解决方案来填充地图中的列表?

这个问题有更优雅的解决方案吗?

有没有更优雅的方式来写这些条件?

有没有更优雅的方法来编写带有重叠(嵌套)替代方案的语句?

有没有更优雅的方式?

有没有更好的解决方案来反转uniq计数

有没有更好的解决方案来卷曲这个 JSON?

有没有比这更好的解决方案来打印结果

“ for”循环的更优雅的解决方案

图形实现更优雅的解决方案?

有没有比forceUpdate()更好的解决方案

有没有更简单的解决方案?

有没有更优雅的方式来重复使用代码块?

有没有更优雅的方法来折叠 dplyr 中的两行?

有没有更优雅的方法来检查表单默认值?

有没有更优雅的方式来启动基于列表的线程?

有没有更优雅的方法来查询多个OR和AND上的多对多表?

有没有更优雅的方法来检查freemarker中的变量?

有没有更优雅的方式来执行这个 switch 语句?

有没有更好/更干净/更优雅的方式来分配和释放cuda?

有没有更优雅的方式来编码此生成器?

有没有更优雅的方式来声明新的 var 并同时使用 global

有没有更优雅的方式来读取CSV列并与记录ID合并?

有没有一种更优雅的方式来代替编写大量查询?

有没有更优雅的方式来编写这个 If/or 条件?

当解决方案是删除冲突的文件时,有没有办法使git rerere工作?

有没有人有更好的解决方案来“迭代地”在Python中应用zip?

有没有更优雅的子串方法?

有没有更短、更优雅的写法?