文件序号前加两个零

问题描述 投票:0回答:3

我是 python 的新手,我想根据文件序列用一个额外的两个零前面的单个数字和一个单独的零来表示 2 位数字来格式化我的文件命名。

我当前的文件命名只是将我的文件重命名为 前任。 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
python python-3.x file-rename
3个回答
0
投票

使用

str.zfill
方法为您的号码添加前导零:

fileSequenceString = str(fileSequence).zfill(3)

因为参数值应该是最终输出的字符串长度,所以在这种情况下是

3
.

在您的代码片段中:

os.rename(folderPath + '\\' + filename, folderPath + '\\' + '1930L' + str(fileSequence).zfill(3) + '.mp3')

0
投票

您可以使用 Python f-Strings 如下

for i in range(0, 10):
  num = f"{i:03d}"
  fn = "1930L" + num + ".mp3"
  print(fn)

产生

1930L000.mp3
1930L001.mp3
1930L002.mp3
1930L003.mp3
1930L004.mp3
1930L005.mp3
1930L006.mp3
1930L007.mp3
1930L008.mp3
1930L009.mp3

在哪里

  • number
    0
    是前导零,
  • number
    3
    是位数,
  • 字母
    d
    是十进制整数。

0
投票

从多个字符串构造路径名时,始终使用 os.path.join 以实现可移植性和可靠性。

对于这个特定问题,f 弦将是理想的选择:

source = os.path.join(folderPath, filename)
target = os.path.join(folderPath, f'1930L{fileSequence:03d}.mp3')
os.rename(source, target)
© www.soinside.com 2019 - 2024. All rights reserved.