Too much code - slicing

DataSmash rdh at new.rr.com
Thu Sep 16 21:35:46 CEST 2010


I need to create a simple utility to remove characters from either the
right or left side of directories.
This works, but there has to be a better way.  I tried to use a
variable inside the brackets but I can't get
that to work.  Can anyone think of a way to do this with less code?
Thanks!

import os

dirs = filter(os.path.isdir, os.listdir(''))
for dir in dirs:

    # Left side
    if num == '1' and side == "l":
        code = dir[1:]
    if num == '2' and side == "l":
        code = dir[2:]
    if num == '3' and side == "l":
        code = dir[3:]
    if num == '4' and side == "l":
        code = dir[4:]
    if num == '5' and side == "l":
        code = dir[5:]
    if num == '6' and side == "l":
        code = dir[6:]
    if num == '7' and side == "l":
        code = dir[7:]
    if num == '8' and side == "l":
        code = dir[8:]
    if num == '9' and side == "l":
        code = dir[9:]
    if num == '10' and side == "l":
        code = dir[10:]
    # Right side
    if num == '1' and side == "r":
        code = dir[:-1]
    if num == '2' and side == "r":
        code = dir[:-2]
    if num == '3' and side == "r":
        code = dir[:-3]
    if num == '4' and side == "r":
        code = dir[:-4]
    if num == '5' and side == "r":
        code = dir[:-5]
    if num == '6' and side == "r":
        code = dir[:-6]
    if num == '7' and side == "r":
        code = dir[:-7]
    if num == '8' and side == "r":
        code = dir[:-8]
    if num == '9' and side == "r":
        code = dir[:-9]
    if num == '10' and side == "r":
        code = dir[:-10]

    print " Renaming "+dir+" to "+code
    os.rename(dir, code)



More information about the Python-list mailing list