Last active
December 24, 2016 19:51
-
-
Save notalentgeek/5ec76b1c10dd0cc135d0a24fc5df96f2 to your computer and use it in GitHub Desktop.
A Python script to mass add same extension to all files in a folder.
This file contains 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
# This is a Python script to mass add same | |
# extension for all files in a folder. | |
import os | |
import shutil | |
import sys | |
def MassAddSameExtension(_targDir, _ext): | |
# Get the list of all files in the targetDirectory. | |
targDirList = os.listdir(_targDir) | |
#print(targDirList) | |
# Remove everything that is directory/folder. | |
targDirListWithoutFolder = [] | |
for fileOrFolder in targDirList: | |
absPathToFileOrFolder = os.path.join( | |
_targDir, fileOrFolder) | |
if not os.path.isdir(absPathToFileOrFolder): | |
targDirListWithoutFolder.append(absPathToFileOrFolder) | |
for file in targDirListWithoutFolder: | |
#print(file) | |
# Split the text into file name and its extension. | |
fileName, ext = os.path.splitext(file) | |
print(fileName) | |
#print(ext) | |
# Check if the second argument has a dot or not. | |
# If the second argument has a dot already, then | |
# do not put additional dot in the front of the | |
# extension. If the second argument has no dot, | |
# then add dot in front of the extension name. | |
#print(str(_ext[:1])) | |
newExt = str(_ext) if str(_ext)[:1] == "." else str("." + _ext) | |
#print(newExt) | |
# Construct new name with new extension | |
# provided from the second argument. | |
#print(fileName) | |
newName = fileName + newExt | |
#print(newName) | |
# Make absolute paths for the old name and | |
# the new name. | |
oldAbsPath = os.path.join(_targDir, file) | |
newAbsPath = os.path.join(_targDir, newName) | |
#print(oldAbsPath) | |
#print(newAbsPath) | |
# Rename the files. | |
print("renamed " + str(file) + " into " + str(newName)) | |
shutil.move(oldAbsPath, newAbsPath) | |
if __name__ == "__main__": | |
MassAddSameExtension(sys.argv[1], sys.argv[2]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment