Add Two Zeroes in front of file sequence number
Question:
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:UsersAdministratorDownloads1930'
fileSequence = 1
for filename in os.listdir(folderPath):
os.rename(folderPath + '\' + filename, folderPath + '\' + '1930L' + str(fileSequence) + '.mp3')
fileSequence +=1
Answers:
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')
You can use Python f-Strings as follows
for i in range(0, 10):
num = f"{i:03d}"
fn = "1930L" + num + ".mp3"
print(fn)
that produces
1930L000.mp3
1930L001.mp3
1930L002.mp3
1930L003.mp3
1930L004.mp3
1930L005.mp3
1930L006.mp3
1930L007.mp3
1930L008.mp3
1930L009.mp3
where
- number
0
is for leading zero,
- number
3
is for number of digits,
- letter
d
is for decimal integer.
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:UsersAdministratorDownloads1930'
fileSequence = 1
for filename in os.listdir(folderPath):
os.rename(folderPath + '\' + filename, folderPath + '\' + '1930L' + str(fileSequence) + '.mp3')
fileSequence +=1
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')
You can use Python f-Strings as follows
for i in range(0, 10):
num = f"{i:03d}"
fn = "1930L" + num + ".mp3"
print(fn)
that produces
1930L000.mp3
1930L001.mp3
1930L002.mp3
1930L003.mp3
1930L004.mp3
1930L005.mp3
1930L006.mp3
1930L007.mp3
1930L008.mp3
1930L009.mp3
where
- number
0
is for leading zero, - number
3
is for number of digits, - letter
d
is for decimal integer.