To remove duplicates from the list
variable just use set()
built-in. And don't use list
as a variable name, this shadows built-in list()
.
Lists are indexed with brackets []
not parens.
I can't see where you're assigning anything but empty list (you wrote it yourself: #List will be empty since for loop has not ran yet
) to targetsrc. Empty list has no elements, so even L[0] will be out of range.
Try something like this:
import os
import shutil
srcpath = "E:\\Learning Python\\Testing out\\thunderstorm stuff"
srcfiles = os.listdir(srcpath)
destpath = "E:\\Learning Python\\Testing out\\test folder"
# extract the three letters from filenames and filter out duplicates
destdirs = list(set([filename[12:15] for filename in srcfiles]))
def create(dirname, destpath):
full_path = os.path.join(destpath, dirname)
os.mkdir(full_path)
return full_path
def move(filename, dirpath):
shutil.move(os.path.join(srcpath, filename)
,dirpath)
# create destination directories and store their names along with full paths
targets = [
(folder, create(folder, destpath)) for folder in destdirs
]
for dirname, full_path in targets:
for filename in srcfile:
if dirname == filename[12:15]:
move(filename, full_path)