Python Fill-Name

I don’t know how you handle it, but if I have a directory of numbered files, I would like them all to have equal length, for that “ls” and autocomplete will show them in appropriate order, but yet I don’t want all the files to consist of let’s say a dozen chars, when five ones would be enough.

So, some days ago I downloaded a couple of files (2469) that were numerated, but without leading “0”, and as 2000 files is quite a lot of work to rename by hand, I wrote this small little Python3-Script that should do the trick for you:

#!/usr/bin/env python3
# This work is licensed under a Creative Commons
# Attribution-ShareAlike 3.0 Unported License.
# I know this is a little uncommon, but who cares.
# The License Terms can be found at
# https://creativecommons.org/licenses/by-sa/3.0/

# You need to call the script from within the directory
# where you want it to rename the files, and it only
# fills with "0" - at least currently.

from os import rename, listdir

def fill_name(file,length):
    if len(file) < length:
        newname="0"+file
        while len(newname) < length:
            newname="0"+newname
        rename(file, newname)

filelist=listdir()

# Here you might want to add additional lines
# such as filename filters.

# Easiest way to find longest filename:
# sort by len get last item
filelist.sort(key=len, reverse=True)
filllength=len(filelist[0])

for curfile in filelist:
    fill_name(curfile,filllength)

return 0

As soon as I get able to do it, I will create a "blog_snippets"-Repo on our Github-Page and push it there, including all changes me or some other f3l-member will do.

Written by pheerai on 15/06/2013 Categories: F3L-Snippet, International corner, Python / Python3 Tags: , ,
Comments Off on Python Fill-Name