我正在寻找一种方法来将带有间隙的图像文件列表重命名为连续的。另外,我想给它们填充 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/