Last active
March 11, 2023 04:32
-
-
Save MacChuck/cbf61ab77e04b8e77aff384139fdbd73 to your computer and use it in GitHub Desktop.
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
import os, shutil, hashlib | |
folderNames = [] | |
startingDir = '.' | |
foldersRootDir = os.path.realpath(startingDir) | |
unsortedFilesDirName = 'Z-Unsorted' | |
unsortedFilesDir = os.path.join(foldersRootDir,unsortedFilesDirName) | |
#create the array of folder names | |
for file in os.listdir(startingDir): | |
if os.path.isdir(file): | |
folderNames.append(file) | |
# go through unsorted files. If file name contains folder name, move that file into the existing folder. Additionally works on files that have hyphens instead of spaces. | |
for folName in folderNames: | |
for file in os.listdir(unsortedFilesDir): | |
if os.path.isfile(os.path.join(unsortedFilesDir,file)): | |
if folName.lower() in file.lower() or folName.lower().replace(" ", "-") in file.lower(): | |
oldLoc = os.path.join(unsortedFilesDir,file) | |
newLoc = os.path.join(foldersRootDir,folName,file) | |
if os.path.exists(newLoc): | |
oldChecksum = hashlib.md5(open(oldLoc, 'rb').read()).hexdigest() | |
newChecksum = hashlib.md5(open(newLoc, 'rb').read()).hexdigest() | |
if oldChecksum == newChecksum: | |
print(f"\u274c {file} {oldChecksum} and {newLoc} {newChecksum} are identical. Moving file to duplicates folder.") | |
duplicatesDir = os.path.join(foldersRootDir, "duplicates") | |
if not os.path.exists(duplicatesDir): | |
os.mkdir(duplicatesDir) | |
duplicateLoc = os.path.join(duplicatesDir, file) | |
shutil.move(oldLoc, duplicateLoc) | |
else: | |
print(f"\u26A0 {file} in both locations are different. Moving file with a modified name.") | |
fileHash = oldChecksum[-6:] | |
fileBase, fileExt = os.path.splitext(file) | |
newLocWithHash = os.path.join(foldersRootDir,folName,f"{fileBase}_{fileHash}{fileExt}") | |
if not os.path.exists(newLocWithHash): | |
print(f"\u2705 Moving {file} to {newLocWithHash}.") | |
shutil.move(oldLoc,newLocWithHash) | |
else: | |
print(f"\u274c {newLocWithHash} already exists. Not moving file.") | |
else: | |
print(f"\u2705 Moving {file} to {newLoc}.") | |
shutil.move(oldLoc,newLoc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could probably do this without the folder names array, or store the file names and folder names in lists to speed up processing and only pull the list of files once.