Reputation: 11
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)
Upvotes: 1
Views: 1674
Reputation: 1
I tried my own approach ... It is kind of ugly but it gets the job done.
import os
import shutil
def sort_folder(fpath: str) -> None:
dirs = []
files = []
filetypes = []
for item in os.listdir(fpath):
if os.path.isfile(f"{fpath}\{item}"):
files.append(item)
else:
dirs.append(item)
for file in files:
filetype = os.path.splitext(file)[1]
filetypes.append(filetype)
for filetype in set(filetypes):
if not os.path.isdir(f"{fpath}\{filetype}"):
os.mkdir(f"{fpath}\{filetype}")
for (file, filetype) in zip(files, filetypes):
shutil.move(f"{fpath}\{file}", f"{fpath}\{filetype}")
if __name__ == '__main__':
# running the script
sort_folder(fpath)
Upvotes: 0
Reputation: 21
os.makedirs
has a switch to create a folder if it does not exist.
use it like this:
os.makedirs(foldern_name, exist_ok=True)
so just replace that try...except part of code which is this:
try:
[os.makedirs(e) for e in ext_final]
except:
print("Folder already exists!")
with this:
for e in ext_final:
os.makedirs(e, exist_os=True)
Upvotes: 2