重命名目录中的文件

2024-05-21 00:18:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个目录中有400个文件(扩展名为.png)。它们以名称005.png开始,一直到395.png。在

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

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

换句话说,我希望将所有数字下移一位,将文件005.png重命名为004.png,并将{}重命名为394.png,依此类推。在

我不想手动执行此操作,因为这会花费太长时间:

^{pr2}$

我怎样才能做到这一点呢?我使用的是s60第二版FP3。在

提前谢谢!在


Tags: 文件目录名称pngos数字手动重命名
3条回答

您可以使用一个简单的循环:

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

就这样:)

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

template = "{0:03d}.png"
for i in range(4, 396):
    os.rename(template.format(i), template.format(i-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)

希望这就是你所期待的

相关问题 更多 >