Skip to content

Instantly share code, notes, and snippets.

@chenrui333
Created February 25, 2015 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chenrui333/a95b0abd1a9d36e6955d to your computer and use it in GitHub Desktop.
Save chenrui333/a95b0abd1a9d36e6955d to your computer and use it in GitHub Desktop.
rename the file names in the dir list
# Import the os module, for the os.walk function
import os
# Set the directory you want to start from
dirs = ['dir1', 'dir2']
prefix = 'abc'
suffix = '_abc'
for dir in dirs:
for dirName, subdirList, fileList in os.walk(dir):
print('Found directory: %s' % dirName)
for fname in fileList:
print('fname: %s' % fname)
filename = os.path.basename(fname).split('.')[0]
ext = os.path.basename(fname).split('.')[1]
print ('basename of fname: %s ' % filename)
if filename.startswith(prefix):
# prefix_*
replace_fname = ''.join([filename.replace(prefix, ''), suffix, '.', ext])
os.rename('\\'.join([dirName, fname]), '\\'.join([dirName, replace_fname]))
else:
if filename.endswith(suffix):
pass
else:
replace_fname = ''.join([filename, suffix, '.', ext])
os.rename('\\'.join([dirName, fname]), '\\'.join([dirName, replace_fname]))
print ('replaced: %s ' % replace_fname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment