I am python newbie and have read countless answers here and in other sources, on how to create folders if they do not exist and move files there. However, still I cannot bring it to work.
So what I want to do is the following: Keep my downloads folder clean. I want to run the script, it is supposed to move all files to matching extension name folders. If the folder already exists, it does not have to create it.
Problems: I want to be able to run the script as often as I want while keeping the newly created folders there. However, then the whole os.listdir part does not work because folders have no file extensions. I tried to solve this by leaving out folders but it does not work as well.
I would appreciate any help!
from os import scandir
import os
import shutil
basepath = r"C:\Users\me\Downloads\test"
for entry in scandir(basepath):
if entry.is_dir():
continue
files = os.listdir(r"C:\Users\me\Downloads\test")
ext = [f.rsplit(".")[1] for f in files]
ext_final = set(ext)
try:
[os.makedirs(e) for e in ext_final]
except:
print("Folder already exists!")
for file in files:
for e in ext_final:
if file.rsplit(".")[1]==e:
shutil.move(file,e)