0

So i wanted to make this little programm to move files depending on their file extension. I came up with this code but it doesn't quite work. Altough it seems like it is executing everything perfectly right, neither folders are created nor are files moved. I don't want the full solution,altough I am not going to say no to it, I am happy about a small hint in the right direction. Looking forward to your answers. :)

import os
import shutil
import sys

filepath = r'C:\\Users\\Markus\\Downloads'
os.chdir(filepath)
l = os.listdir(filepath)

for file in l:
    print(os.path.splitext(file)[1])
    print(file)
    folder = os.path.splitext(file)[1]
    file_name = file
    file_path = os.path.abspath(file_name)  
    try:
        # if folder exists move to this folder
        shutil.move(file_name, folder)
        print("Moved to folder " + folder + " !")
    except:
        # if folder does not exist create and then move to the folder
        os.makedirs(filepath, exist_ok=True)
        print("New folder created!")
        shutil.move(file_name, file_path)
        print("Moved to folder " + folder + " !")
  • Two comments: 1. os.listdir() lists files and folders - see https://stackoverflow.com/questions/22207936/how-to-find-files-and-skip-directories-in-os-listdir 2. in os.makedirs() do you want ```filepath``` or ```file_path```? Using variable with so similar names can lead to confusion. – fdireito Feb 21 '21 at 19:59
  • Thank you so much. – Botsl 04 Feb 22 '21 at 20:23

0 Answers0