breaking from loop

Peter Otten __peter__ at web.de
Fri Feb 10 03:53:41 EST 2006


Ritesh Raj Sarraf wrote:

> Following is the code:
> 
> def walk_tree_copy(sRepository, sFile, sSourceDir, bFound = None):
>     try:
>         if sRepository is not None:
>             for name in os.listdir(sRepository):
>                 path = os.path.join(sRepository, name)
>                 if os.path.isdir(path):
>                     walk_tree_copy(path, sFile, sSourceDir, bFound)
>                 elif name.endswith('.foo') or name.endswith('.bar'):
>                     if name == sFile:

Pick /one/ the conditions

- file name must be ...
- file must end with ... or ...

>                         try:
>                             shutil.copy(path, sSourceDir)
>                         except IOError, (errno, errstring):
>                             errfunc(errno, errstring)
>                         except shutil.Error:
>                             print name + " is available in " +
> sSourceDir + "Skipping Copy!"
>                         bFound = True
>                         break
>                         return bFound
>     except OSError, (errno, strerror):
>         print errno, strerror
> 
> This function allows me to walk into a directory based tree and search
> for files ending with .foo and .bar. My requirement is to copy
> .foo/.bar.
> Say in directory temp=>test=>test.bar is found. So shutil.copy will
> copy it. I want that once the copy is done, it should make bFound =
> True and get out.
> But since test directory is under temp, work_tree_copy makes two calls
> of the same function _but_ break only is able to get out from the inner
> call.
> 
> Where am I wrong in this code ? Is there a better way to implement it ?

An implementation on top of os.walk() can simplify things a bit:

import os
import shutil

def files(root):
    for path, folders, files in os.walk(root):
        for file in files:
            yield path, file

def copy_first_match(repository, filename, dest_dir): # aka walk_tree_copy()
    for path, file in files(repository):
        if file == filename:
            shutil.copy(os.path.join(path, file), dest_dir)
            return True
    return False

files() and os.walk() take care of the recursion, and you can just break or
return from the loop in copy_first_match(). 

Peter




More information about the Python-list mailing list