copying files through Python

Larry Bates larry.bates at websafe.com
Wed Feb 13 17:18:19 EST 2008


Lalit wrote:
> I am new to python. Infact started yesterday and feeling out of place.
> I need to write a program which would transfer files under one folder
> structure (there are sub folders) to single folder. Can anyone give me
> some idea like which library files or commands would be suitable for
> this file transfer task. I am sure its matter of few commands. It
> would be even more great if I could get some sample code with
> instructions
> 
> Thanks

You should use walk() method from os module and use the copy method from shutil 
module.  I'm assuming when you say "transfer" you mean "move".

Something like (not tested)

import os
import shutil

# src='source path'
# dst='destination path'

for root, dirs, files in os.walk(src):
     for f in files:
         srcfile=os.path.join(root, f)
         print "move '%s'->'%s'" % (srcfile, dst)
         shutil.move(os.path.join(root, f), dst)


-Larry Bates



More information about the Python-list mailing list