[Tutor] How can I copy files recursively?
John Fouhy
john at fouhy.net
Tue Jul 11 06:15:09 CEST 2006
On 11/07/06, Richard Querin <rfquerin at gmail.com> wrote:
> I know this is probably a dumb question:
>
> I've got mp3 files that are downloaded (by ipodder) into individual
> subfolders. I'd like to write a quick script to move (not copy) all the mp3
> files in those folders into a single destination folder. I was thinking I
> could do it easily from the linux command line (cp -r copies the subfolders
> out as well) but I can't figure out how to do it. Is there an easy way to
> achieve this using Python? I am assuming this would be something Python was
> designed to make easy..
You could do it from the command line with something like:
$ for f in `find ./ -name *.mp3`; do mv $f /foo/bar/$f; done
(actually, that won't work; you'll need to find a way to convert
"/x/y/z.mp3" to "z.mp3". I don't have a linux commandline handy to
test.. basename, maybe? You could do it with awk --
$ for f in `find ./ -name *.mp3`; do mv $f /foo/bar/`echo $f | awk -F
'/' '{print $NF}'`; done
but that's pretty hairy and may not work :-/
)
In python, you can use os.rename to move and os.walk to walk your
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))
(although I would do a test run first, if I were you, since I often
get os.walk wrong :-) )
--
John.
More information about the Tutor
mailing list