重命名目录中的文件

时间:2012-08-19 13:50:21

标签: python

我在目录中有400个文件(扩展名为.png)。他们从名称005.png开始,然后到395.png

我想使用os.rename重命名它们:

os.rename(006.png,005.png)

换句话说,我想将所有数字向下移动一个,将文件005.png重命名为004.png并将395.png重命名为394.png,依此类推。< / p>

我不想手动执行此操作,因为这需要太长时间:

os.rename(005.png,004.png)
os.rename(006.png,005.png)
...

我怎么能这么做呢?我正在使用s60第二版FP3。

提前致谢!

3 个答案:

答案 0 :(得分:3)

您可以使用简单的循环:

for i in xrange(4, 396):
    os.rename(str(i).zfill(3) + ".png", str(i-1).zfill(3) + ".png"))

就是这样:)

答案 1 :(得分:2)

循环是最简单的。作为str(i).zfill(3) + ".png"的替代方案,您可以使用

template = "{0:03d}.png"
for i in range(4, 396):
    os.rename(template.format(i), template.format(i-1))

答案 2 :(得分:1)

import os
path  = r"C:\your_dir"#i've added r for skipping slash , case you are in windows
os.chdir(path)#well here were the problem , before edit you were in different directory and you want  edit file which is in another directory , so you have to change your directory to the same path you wanted to change some of it's file 
files = os.listdir(path)
for file in files:
    name,ext = file.split('.')
    edited_name=str(int(name)-1)
    os.rename(file,edited_name+'.'+ext)

希望这就是你想要的东西

相关问题