Add leading zeros to filename

Question:

I have a folder with more than 1.000 files that’s updated constantly. I’m using a script to add a random number to it based on the total of the files, like this:

Before

file_a
file_b

After

1_file_a
2_file_b

I would like to add leading zeros so that the files are sorted correctly. Like this:

0001_file_a
0010_file_b
0100_file_c

Here’s the random number script:

import os
import random

used_random = []

os.chdir('c:/test')
for filename in os.listdir():
    n = random.randint(1, len(os.listdir()))
    while n in used_random:
        n = random.randint(1, len(os.listdir()))
    used_random.append(n)
    os.rename(filename, f"{n}_{filename}")
Asked By: shinjidf

||

Answers:

I would suggest using f-strings to accomplish this.

>>> num = 2
>>> f"{num:04}_file"
'0002_file'
>>> num = 123
>>> f"{num:04}_file"
'0123_file'

I would also replace the following with a list comprehension.

cleaned_files = []
for item in folder_files:
   if item[0] == '.' or item[0] == '_':
       pass
   else:
       cleaned_files.append(item)
cleaned_files = [item for item in folder_files if not item[0] in ('.', '_')]
Answered By: Chris

You should use the first element of the list obtained after split:

def getFiles(files):
    for file in files:
        file_number, file_end = file.split('_')
        num = file_number.split()[0].zfill(4)  # num is 4 characters long with leading 0

        new_file = "{}_{}".format(num, file_end)
        # rename or store the new file name for later rename
Answered By: Adrian B

Something like this should work … I hope this helps …

import re
import glob
import os
import shutil

os.chdir('/tmp')  # I played in the /tmp directory

for filename in glob.glob('[0-9]*_file_*'):
    m = re.match(r'(^[0-9]+)(_.*)$', filename)
    if m:
        num = f"{int(m.group(1)):04}"  # e.g. 23 convert to int and than format
        name = m.group(2)  # the rest of the name e.g. _file_a
        new_filename = num + name  # 0023_file_a
        print(filename + " " + new_filename)
        # Not sure if you like to rename the files, if yes:
        # shutil.move(filename, new_filename)
Answered By: Gusiph

Thanks to user https://stackoverflow.com/users/15261315/chris I updated the random number script to add leading zeros:

import os
import random

used_random = []

os.chdir('c:/Test')
for filename in os.listdir():
    n = random.randint(1, len(os.listdir()))
    while n in used_random:
        n = random.randint(1, len(os.listdir()))
    used_random.append(n)
    os.rename(filename, f"{n:04}_{filename}")
Answered By: shinjidf
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.