python-----重命名文件(在原文件名前加0)

问题描述:

如果用循环给文件命名,则文件名就会是1,2,3...,10,11,12,13...,100,101...,但是遍历这些文件时,顺序就会变成1,10,100,101,...109,11,...,19,...,2,20,200,...,那么如何按1,2,3,4....的顺序遍历呢?

解决方法:

可以把原来的文件重命名,在原文件名前面加上0,例如00001,00002,...,这样就可以按顺序遍历了。代码如下:

import os

path =r'E:105	xt'
for file in os.listdir(path):
    name = file.split('.')[0]
    os.rename(os.path.join(path, file), os.path.join(path, '%05d' % int(name) + ".txt"))   #‘%05d’表示一共5位数
原文地址:https://www.cnblogs.com/xiaodai0/p/10224097.html