[Tutor] How can I copy files recursively?
Kent Johnson
kent37 at tds.net
Tue Jul 11 13:07:54 CEST 2006
John Fouhy wrote:
> 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..
>>
>
> 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))
This will copy all the files into the dest directory - it doesn't copy
the folder structure.
I highly recommend Jason Orendorff's path module for any code involving
walking directories. Something like this:
from path import path
source = path('/ipodder')
dest = '/foo/bar'
for mp3 in source.walkfiles('*.mp3'):
relpath = source.relpathto(mp3)
destmp3 = dest / relpath
os.rename(mp3, destmp3)
http://www.jorendorff.com/articles/python/path/index.html
Kent
More information about the Tutor
mailing list