Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# -*- coding: utf8 -*-
USAGE = \
'''
USAGE:
rename
$ python rename.py rn {oldName} {newName}
copy & rename
$ python rename.py cp {oldName} {newName}
'''
import glob
import re
import os, sys
import distutils.dir_util
import shutil
args = sys.argv
if (len(args) != 4):
print("Need correct argments.")
print(USAGE)
sys.exit()
command = args[1]
srcName = args[2]
dstName = args[3]
reg = re.compile("^.*?"+srcName+".*$")
if os.path.isdir(srcName) == False:
print("No such directory", srcName)
sys.exit()
if (os.path.exists(dstName)):
print("dst dir already exists:", dstName)
sys.exit()
def replaceNameInfile(filePath, src, dst):
with open(filePath, 'r', encoding="utf_8_sig") as f:
newText = f.read().replace(src, dst)
pass
with open(filePath, "w", encoding="utf-8-sig") as f:
f.write(newText)
pass
print('Replaced text from', src, 'to', dst, 'in file:', filePath)
return
def renameProject(projectPath, src, dst):
projDir = os.path.abspath(projectPath)
print('[start rename project files]')
print('Project dir:', projDir)
files = os.listdir(projDir)
print('-----')
for file in filter(lambda name: reg.match(name) != None, files):
print('[Rename file]', file)
filePath = os.path.abspath(projDir + "/" + file)
if re.match(r"^.+?.db$", filePath):
os.remove(filePath)
print("Deleted file:", file)
continue
pass
elif (re.match(r"^.+?.sdf$", filePath)):
os.remove(filePath)
print("Deleted file:", file)
continue
pass
else:
replaceNameInfile(filePath, src, dst)
pass
extentions = os.path.basename(filePath).split('.')
extentions.pop(0)
ext = '.'.join(extentions)
newPath = os.path.join(projDir, dst+'.'+ext)
os.rename(filePath, newPath)
print('Renamed:', filePath, " to ", newPath, '\n')
pass
return
if command == 'rn':
shutil.move(srcName, dstName)
renameProject('./'+dstName, srcName, dstName)
elif command == 'cp':
distutils.dir_util.copy_tree(srcName, dstName)
renameProject("./"+dstName, srcName, dstName)
else:
print('unknown command:', command)
print(USAGE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment