recursive using the os.walk(path) from the os module

Fredrik Lundh fredrik at pythonware.com
Wed Sep 17 08:42:25 EDT 2008


A. Joseph wrote:

> I want to search through a directory and re-arrange all the files into e.g
> 
> All .doc files go into MS WORD folder, all .pdf files goes into PDF Folder.
> 
> I`m thinking of doing something with the os.walk(path) method from os 
> module, I need some ideal how the algorithm should look like, maybe 
> recursive ..any deal?

os.walk traverses the directory tree, so I'm not sure why you think that 
your program needs to use recursion?  wouldn't a plain loop work?

     import os, shutil

     for dirpath, dirnames, filenames in os.walk(directory):
         for name in filenames:
             source = os.path.join(dirpath, name)
             ... check extension and determine target directory ...
             destination = os.path.join(targetdir, name)
             shutil.move(source, destination)

tweak as necessary.

</F>




More information about the Python-list mailing list