Anything better than shutil?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Nov 14 23:29:44 EST 2009


On Sat, 14 Nov 2009 07:48:39 -0800, Roy Smith wrote:

> I'm converting some old bash scripts to python.  There's lots of places
> where I'm doing things like "rm $source_dir/*.conf".  The best way I can
> see to convert this into python is:
> 
>     configs = glob.glob(os.path.join(source_dir, '*.conf')) 
>     for conf_file in configs:
>         shutil.copy(conf_file, conf_dir)
> 
> which is pretty clunky.

Particularly since you're converting a remove to a copy...

I suppose if you're used to the sort of terse code filled with magic 
characters that you find in bash, then the Python code might seem a bit 
verbose. And I suppose you would be right :) But trying to do something 
complicated in bash rapidly becomes *far* more verbose, unreadable and 
clunky than Python.



> The idea interface I see would be one like:
> 
>   shutil.copy([source_dir, '*.conf'], conf_dir)

Then write a helper function, and call that.

# Untested.
def copy(glb, destination):
    if not isinstance(glb, str):
        glb = os.path.join(*glb)
        glb = glob.glob(glb)
    for source in glb:
        shutil.copy(source, destination)



-- 
Steven



More information about the Python-list mailing list