Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add Two Zeroes in front of file sequence number

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading