问题描述:

如果用循环给文件命名,则文件名就会是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:\0105\txt'
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位数

 

相关文章:

  • 2021-09-26
  • 2022-12-23
  • 2022-12-23
  • 2021-06-18
  • 2021-10-16
  • 2021-06-15
  • 2022-02-07
猜你喜欢
  • 2021-06-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-29
  • 2022-02-13
  • 2021-12-30
相关资源
相似解决方案