May-06-2018, 02:06 AM
(May-04-2018, 10:51 PM)killerrex Wrote: Hi Shakir, What I was saying is that it can be better to avoid the chdir altogether. Changing the current directory is practical for dirty code in the command line and some really obscure special occasions, but normally is just a source of bugs... This code is what I manage to understand from tour explanation (maybe I got wrong the idea of what you want to do, but look to the tools to play with paths and adapt it to your code)Thank you soooooo much killerrex. This works EXACTLY how I needed it to. I'm now going to do myself a favor and go through Google's free 2 day Python course and also take advantage of a few of the available free online courses. I really like Python. One question; after looking at the last part of your code, beginning on like 32, how would I have known to do that? Being a noob and all. Thanks again.#!/usr/bin/python3 import os import shutil import sys import fnmatch top_dir = "/home/mmcneil/Desktop/TMP" root_dir = [d.name for d in os.scandir('.') if d.is_dir()] mapping = { 'Blaster': 'blaster*', 'Clash': 'clash*', 'Force': 'force*', 'Lockup': 'lockup*', 'PowerOFF': 'p*w*off*', 'PowerON': 'p*w*on*', 'Sign1': 'combo*', 'Spin': 'spin*', 'Stab': 'stab*', 'Swing': 'swing*' } ## Create for all the folders in the current directory a set of subdirectories # So if the current directory has the folders a, b, c everything finish as # ./a/Blaster ./b/Blaster ./c/Blaster # ./a/Clash ./b/Clash ./c/Clash # ./a/... ./b/... ./c/... for root_folder in root_dir: for section in mapping: os.makedirs(os.path.join(root_folder, section), exist_ok=True) ## Everthing ABOVE this line works the way I want it to## ## Try to move all the files that are under top_dir/<Folder>/<glob> to ## ./<Folder>/<section>/ for ret_folder in root_dir: source = os.path.join(top_dir, ret_folder) # List all the files in the source for entry in os.scandir(source): if not entry.is_file(): continue for section, pattern in mapping.items(): if not fnmatch.fnmatch(entry.name, pattern): continue # Move top_dir/<Folder>/file to ./<Folder>/<section>/ ori = os.path.join(source, entry.name) dst = os.path.join('.', ret_folder, section) shutil.move(ori, dst) breakI think the problem in your code was in the linefor file in os.path.join(top_dir, ret_folder):That does not list all the files in the directory "<top_dir>/<ret_folder>" but iterate over the characters in the string (so file was "/", "h", "o", "m", "e"...) That is one of the advantages of python (you can iterate in almost anything) but sometimes is not what you want to do. To solve this type of problems the best thing is to put some traces in your code or use a debugger to put a breakpoint before the loop.
Shakir