modify file name util - python
a util script to modify file/folder name recusively, written in python, on ubuntu system,
code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: eric
# @date: 03/04/2012 00:09 am
# @mail: kuchaguangjie@163.com
# this is a python util to modify file names, replace substring in file/folder name with another substring, recursively.
# you should modify variable 'basic_dir' / 'c' / 'c_new', before run this script
# everything, include file/folder recurisively, under the 'basic_dir' will be rename,
# how to run this script, just "./xxx.sh"
# ps: backup before modify is good manners.
import os
import shutil
# basic dir to where files resides
basic_dir = "/tmp/test/"
# substring to replace
c = " "
# new substring
c_new = " "
# function to modify file name recursively
def modify_name(dir,c,c_new):
# check whether the 2 substring are the same
if c == c_new:
print ("2 substring are the same, no need to change")
return True
# add '/' to dir end, if necessary,
if not dir.endswith('/'):
dir += '/'
# check dir exists
if os.path.isdir(dir):
print ("dir is: "+dir)
else:
print ("dir not exist:" + dir)
return False
# file list
filelist=[]
filelist=os.listdir(dir)
# iterator filelist
for fname in filelist:
# change file name if need
if fname.find(c) >= 0:
fname_new=fname.replace(c, c_new)
print fname_new
shutil.move(dir+fname,dir+fname_new)
fname = fname_new
# call the function recurisively on the sub dir
if os.path.isdir(dir+fname):
modify_name(dir+fname,c,c_new)
# the entry, call the function, with the basic dir
modify_name(basic_dir,c,c_new);