-1

Beginner here. I want to be able to traverse folders and their subdirectorys and files and move all unique file extensions into a dedicated folder for that filetype. Ex .jpg -> into jpg folder. (This is all in Python's IDLE)

I have this code:

os.chdir('c:\\users\\dchrie504\\Downloads_2')
# walk through all files and folders to get unique filetypes.
l_Files = os.walk('c:\\users\\dchrie504\\Downloads_2')
fileTypes = []
for walk in l_Files:
    for file in walk[-1]:
        fileTypes.append(file.split('.')[-1])
# make all items lowercase to create distinct values
fileTypes = [x.lower() for x in fileTypes]

# get rid of duplicate filetypes by creating set then back to list. 
fileTypes = set(fileTypes)
fileTypes = list(fileTypes)
# create a folder for each unique filetype. 
for ft in fileTypes:
    os.mkdir(os.getcwd() + '\\' + ft)
fileWalk = os.walk('c:\\users\\dchrie504\\Downloads_2')

#Trying to move files to their respective fileType folder.
for fileType in fileTypes:
     for folder, sub, files in os.walk('c:\\users\\dchrie504\\Downloads_2'):
         for file in files:
             if file.endswith('.' + fileType):
                 shutil.move(file, (os.getcwd() + '\\' + fileType))

Problem is I get the following error when this part executes:

         for file in files:
             if file.endswith('.' + fileType):
                 shutil.move(file, (os.getcwd() + '\\' + fileType))

Error Message: Traceback (most recent call last): File "", line 5, in shutil.move(file, (os.getcwd() + '\' + fileType)) File "C:\Users\dchrie504\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 555, in move raise Error("Destination path '%s' already exists" % real_dst) shutil.Error: Destination path 'c:\users\dchrie504\Downloads_2\txt\New Text Document.txt' already exists

dmc30
  • 1
  • 1

1 Answers1

0

you have to give the full path so shutil.move will overwrite.

shutil.move(fullpathorigin, fullpathdestination)
Astrom
  • 767
  • 5
  • 20
  • Like this? for fileType in fileTypes: for folder, sub, files in os.walk('c:\\users\\dchrie504\\Downloads_2'): for file in files: if file.endswith('.' + fileType): shutil.move((os.getcwd() + '\\' + file), (os.getcwd() + '\\' + fileType)) Even with this code ^ I still get the following : shutil.Error: Destination path c:\users\dchrie504\Downloads_2\jpg\53aabe7s4b721.jpg' already exists – dmc30 Feb 05 '19 at 20:02