Add Two Zeroes in front of file sequence number

Advertisements

I’m fairly new to python and I want to format my filenaming with an extra two zeros infront for single digit and a single zero for 2 digit numbers depending on the file sequence.

My current file naming just renames my file like
ex. 1930L1.mp3

I want it to be 1930L001.mp3

Here is my code

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

>Solution :

Use str.zfill method to add leading zeroes to your number:

fileSequenceString = str(fileSequence).zfill(3)

As parameter value should be final output string length, so in this case it’s 3.

In your code snippet:

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

Leave a ReplyCancel reply