简体   繁体   中英

sorting folders in a directory ( combination of alphabets and numbers) in python

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])

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM