0

I want to revise folder's names in a directory and sort them, I would be grateful if someone could possibly help me with that.

for instance: I have a directory which includes sam1 .... sam100000( preferably we don't know about the how many folders we have) . what I want in the output directory sorting and revising the names in the way that for instance if the last folder has 6 digits the first folder would look like sam000001 ( adding 5 zeros ) and for sam15 it would be sam000015 (adding 4 zeros).

thanks in advance

import os
import os.path  

E = 0

for _, dirnames, filenames in os.walk('path'):


    E += len(dirnames)

formating= "{0:6}"
enum=["{0:6}".format(i) for i in range (1,E)]
original=[i for i in range (1,E)]
start='sam'
for i in original :
    os.rename(start+str(i),start+enum[i])
Sam
  • 1
  • 1
  • Welcome Sam! Try to be more concise in your question and show that you put some thought into it yourself. You might want to take a look at the [os library](https://docs.python.org/3/library/os.html) and this [related question](https://stackoverflow.com/questions/168409/how-do-you-get-a-directory-listing-sorted-by-creation-date-in-python) – 465b Apr 22 '20 at 20:13

1 Answers1

0

From a folder name, you need 2 things

  • the new name : build the format "{}{:0%sd}" % padding_size => "{}{:06d}"

    oldname = "folder15"
    padding_size = 6
    
    parts = re.search("(.*?)(\d+)", oldname).groups()
    newname = ("{}{:0%sd}" % padding_size).format(parts[0], int(parts[1]))
    print(newname) # folder000015
    
  • rename it using os.rename(oldpath, newpath)

azro
  • 53,056
  • 7
  • 34
  • 70
  • thanks, but I have a directory which has so many folders inside ( I don't want to open GUI to see ), but what I know from some information is that folders inside are starting with names like u mentioned folder+digits . what I want to do is to write a code that get the directory and iterate through all the folders inside the directory( not what contains inside the folders) and revise all the digit part of their names so that the have same size of digits ( as u gave an example folder15 >>> folder000015 ) , but this adding should be done automatically not that I give it to the code. – Sam Apr 23 '20 at 08:50