May-03-2018, 10:07 AM
Hi,
You are using os.walk to access to the current directory, but remember that os.walk will transverse the entire folder tree. If you only want to list the current directory is enough with os.listdir or even better os.scanlist.
As a small recommendation, try to chdir as less as possible. In your case all the loop can work without having to move the execution directory as shutil.move works fine with absolute paths (os.getcwd allows you to obtain the current folder full path).
Another nice trick to avoid repeating the same fnmatch schema is to store them in a dictionary. If it is {mask: Folder} that many masks can go to the same directory, if you use the opposite {Folder: mask} each folder can only contain one set of files.
You are using os.walk to access to the current directory, but remember that os.walk will transverse the entire folder tree. If you only want to list the current directory is enough with os.listdir or even better os.scanlist.
# List all the elements of the current directory that are folders folders = [d.name for d in os.scandir('.') if d.is_dir()]I think the problem is when you try to chdir in the 'top_dir/root_dir'... the last for loop (the one in the line 23) is supposed to work for each of the ret_folder values, but as it is outside of the for in line 19 it only runs for the last value and remember that os.walk returns the folders in no particular order.
As a small recommendation, try to chdir as less as possible. In your case all the loop can work without having to move the execution directory as shutil.move works fine with absolute paths (os.getcwd allows you to obtain the current folder full path).
Another nice trick to avoid repeating the same fnmatch schema is to store them in a dictionary. If it is {mask: Folder} that many masks can go to the same directory, if you use the opposite {Folder: mask} each folder can only contain one set of files.
mapping = {'Blaster': 'blaster*', 'Clash': 'clash*'} # And all the others... # for file in os.listdir('.'): for file in os.path.join(top_dir, ret_folder): for target in mapping: if fnmatch.fnmatch(file, mapping[target]): shutil.move(file, target)