Home > Net >  Python - add leading zeros to filename
Python - add leading zeros to filename

Time:01-05

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

I found this code in another question and after updating with bellow suggestions the script does nothing:

import os
from tkinter import filedialog

cleaned_files = []

os.chdir('folder')
folder_files = os.listdir('folder')

# Filter out files starting with '.' and '_'
cleaned_files = [item for item in folder_files if not item[0] in ('.', '_')]
# Find file names of the root folder and save them

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

getFiles(cleaned_files)

CodePudding user response:

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 ('.', '_')]

CodePudding user response:

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
  • Related