Last active
June 14, 2017 16:00
-
-
Save mgrandi/547d68114c0768edbbee to your computer and use it in GitHub Desktop.
rename a file based on the name of the parent directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# script to rename files to the same name as the parent folder | |
# | |
# so | |
# | |
# 3a -| | |
# - 3a1c603a -| | |
# - resident_sound.dat (gets renamed to be 3a1c603a_resident_sound.dat) | |
# | |
# | |
# written by Mark Grandi - Jun 11, 2014 | |
# | |
import argparse, sys, re, os.path, os | |
def renameFilesToParentFolder(args): | |
'''renames files to include the parent folder's name | |
@param args - the namespace object we get from argparse.parse_args() | |
''' | |
if args.verbose: | |
print("Regex is: '{}'".format(args.fileToRenameRegex)) | |
print("Searching directory: '{}'".format(args.inputFolder)) | |
# dirpath is a string, the path to the directory. | |
# dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). | |
# filenames is a list of the names of the non-directory files in dirpath. | |
for dirpath, dirnames, filenames in os.walk(args.inputFolder): | |
for iterFile in filenames: | |
curPath = os.path.join(dirpath, iterFile) | |
if args.fileToRenameRegex.search(iterFile) != None: | |
if args.verbose: | |
print("file {} matched, renaming".format(curPath)) | |
# get the parent name | |
pName = os.path.split(os.path.dirname(curPath))[1] | |
# this only happens if we are at root for some reason? | |
if pName == "": | |
pName = "ROOT" | |
# get extension | |
ext = os.path.splitext(iterFile)[1] | |
oldName = os.path.splitext(iterFile)[0] | |
newPath = os.path.join(dirpath, "{}_{}{}".format(oldName, pName, ext)) | |
# rename the file | |
os.replace(curPath, newPath) | |
print("{} renamed to {}".format(curPath, newPath)) | |
else: | |
if args.verbose: | |
print("file {} did not match regex, skipping".format(curPath)) | |
print("done!") | |
def isDirectoryType(stringArg): | |
''' helper method for argparse to see if the argument is a directory | |
@param stringArg - the argument we get from argparse | |
@return the path if it is indeed a directory, or raises ArgumentTypeError if its not.''' | |
path = os.path.realpath(os.path.normpath(stringArg)) | |
if not os.path.isdir(path): | |
raise argparse.ArgumentTypeError("{} is not a directory!".format(path)) | |
return path | |
def isRegexType(stringArg): | |
''' helper method for argparse to see if the argument is a valid regex expression | |
@param stringArg - the argument we get from argparse | |
@return the compiled RE object if it is indeed a directory, or raises ArgumentTypeError if its not.''' | |
compiledRe = None | |
try: | |
compiledRe = re.compile(stringArg) | |
except re.error as e: | |
# not a valid regex expression | |
raise ArgumentTypeError("{} is not a valid regular expression! error: {}".format(stringArg, e)) | |
return compiledRe | |
if __name__ == "__main__": | |
# if we are being run as a real program | |
parser = argparse.ArgumentParser(description="renames files to include the parent folder's name", | |
epilog="Copyright Jun 11, 2014 Mark Grandi") | |
# optional arguments, if specified these are the input and output files, if not specified, it uses stdin and stdout | |
parser.add_argument('inputFolder', type=isDirectoryType, help="the folder that contains the files to rename") | |
parser.add_argument('fileToRenameRegex', type=isRegexType, help="the regex to use to figure out what files to rename, " | |
"if unsure just type the entire name (like 'resident_sound.dat')") | |
parser.add_argument("--verbose", action="store_true", help="use this to increase verbosity") | |
renameFilesToParentFolder(parser.parse_args()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment