[Tutor] How can I copy files recursively?
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Tue Jul 11 08:05:13 CEST 2006
> directory structure. Something like:
>
> source = '/ipodder'
> dest = '/foo/bar'
> for root, dirs, files in os.walk(source):
> for f in files:
> os.rename(os.path.join(root, f), os.path.join(dest, f))
A helper function here will be useful. We can simulate something like:
find . -name '*.mp3'
with:
#####################################################
import os, fnmatch
def find_with_glob(dir, pattern):
"""find_with_glob: string string -> listof(string)
Returns a list of all the files that can be found
in dir or subdirectories, matching the globbing pattern.
For example: find_with_glob('.', '*.mp3').
"""
results = []
for root, dirs, files in os.walk(dir):
for f in files:
if fnmatch.fnmatch(f, pattern):
results.append(os.path.join(root, f))
return results
#####################################################
The reason this ends up a bit verbose compared to the shell is because the
shell's 'find' utility is doing a lot of work too. But if we were to do a
simple lookup for mp3 files, I agree that using Unix's 'find' would be the
simplest approach.
One advantage we have in using Python here is generality: we can, with a
little work, plug in a different kind of filter here: rather than use
globs, we can use full-fledged regular expressions.
More information about the Tutor
mailing list