Python实现文件名序列号补零格式化:将序列转为三位带前导零
文件名序列号三位格式化解决方案
需求说明
需要将文件名中的序列号统一为三位格式:
- 单数字序列号(如1)补两个零,变为
001 - 两位数字序列号(如12)补一个零,变为
012
当前代码生成的文件名示例为1930L1.mp3,期望输出1930L001.mp3
现有代码
import os folderPath = r'C:\Users\Administrator\Downloads\1930' fileSequence = 1 for filename in os.listdir(folderPath): os.rename(folderPath + '\\' + filename, folderPath + '\\' + '1930L' + str(fileSequence) + '.mp3') fileSequence +=1
修改后的代码
推荐两种实现方式,任选其一即可:
方式1:使用f-string格式化(Python 3.6+)
import os folderPath = r'C:\Users\Administrator\Downloads\1930' fileSequence = 1 for filename in os.listdir(folderPath): # 用:03d指定数字格式为三位,自动补零 new_filename = f'1930L{fileSequence:03d}.mp3' os.rename(os.path.join(folderPath, filename), os.path.join(folderPath, new_filename)) fileSequence += 1
方式2:使用str.zfill()方法
import os folderPath = r'C:\Users\Administrator\Downloads\1930' fileSequence = 1 for filename in os.listdir(folderPath): # zfill(3)会在字符串左侧补零,直到长度为3 new_filename = '1930L' + str(fileSequence).zfill(3) + '.mp3' os.rename(os.path.join(folderPath, filename), os.path.join(folderPath, new_filename)) fileSequence += 1
额外优化说明
- 替换了原代码中直接拼接路径的写法,改用
os.path.join(),它会自动适配不同操作系统的路径分隔符,避免出现路径错误 - 两种格式化方式都能实现需求,f-string写法更直观易读,zfill()方法兼容性稍好(支持更早的Python版本)
内容的提问来源于stack exchange,提问作者Noscire Designs
相关产品推荐
相关产品推荐

