python - 重命名有间隙的连续图像文件

标签 python linux bash

我正在寻找一种方法来将带有间隙的图像文件列表重命名为连续的。另外,我想给它们填充 4。我目前正在使用 Python 2.7 和 Linux bash 来对此进行编程。

    Example:

    1.png
    2.png
    3.png
    20.png
    21.png
    50.png

应该变成:

    0001.png
    0002.png
    0003.png
    0004.png
    0005.png
    0006.png

我还希望文件名与它们当前所在的目录相同。

    Example:

    c_users_johnny_desktop_images.0001.png
    c_users_johnny_desktop_images.0002.png
    c_users_johnny_desktop_images.0003.png
    c_users_johnny_desktop_images.0004.png
    c_users_johnny_desktop_images.0005.png
    c_users_johnny_desktop_images.0006.png

任何帮助将不胜感激! :)

干杯

最佳答案

这是Python

#first collect all files that start with a number and end with .png
my_files = [f for f in os.listdir(some_directory) if f[0].isdigit() and f.endswith(".png")]
#sort them based on the number  
sorted_files = sorted(my_files,key=lambda x:int(x.split(".")[0])) # sort the file names by starting number
#rename them sequentially
for i,fn in enumerate(sorted_files,1): #thanks wim
    os.rename(sorted_files[i],"{0:04d}.png".format(i))

我本可以使用 list.sort(key=...) 进行就地排序,但我认为这会更加冗长和可读......

关于python - 重命名有间隙的连续图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280528/

相关文章:

C 应用程序在连接到服务器时卡住

regex - 在 Linux 中,名称与正则表达式匹配的文件的磁盘使用情况?

Bash 命令值赋值

python - 不了解页面结构的网页抓取

Python 正则表达式 : Add "-" inside a string using re. 子

linux - Unix:在位于不同路径的文件中搜索单词

Linux shell 脚本按字母顺序对文本行进行反向排序(最好不使用排序)

git - 如何在 bash 脚本中检查空的 cherry-picks?

python - 属性错误: module 'sklearn' has no attribute 'model_selection'

python - Linux 将相同的 .py 文件识别为不同的