rename strings / rename files in python

1.4k views Asked by At

I have a bunch of files like below:

_1 blank file_
_10 - blank file_
_11 - blank file_
_2 blank file_
_3 blank file_

I would like to print out the name with the numbers padded (2 characters)

I have :

PATH = "/Users/seth/python/test"
#
#
for (path, dirs, files) in os.walk(PATH):

    for z in  files:

        filename = z.replace(" ","_").replace("-","").replace("__","_")
        print filename

Desired Output:

_01_blank_file_

_02_blank_file_

_03_blank_file_

_10_blank_file_

_11_blank_file_

1

There are 1 answers

2
Niklas B. On BEST ANSWER

You can use rjust for that:

for (path, dirs, files) in os.walk(PATH):
  for z in files:
    filename = z.replace(" ","_").replace("-","").replace("__","_")

    # explode and transform number
    parts = filename.split('_', 2)
    parts[1] = parts[1].rjust(2, '0')

    # rejoin the transformed parts
    print '_'.join(parts)