copying files through Python

Tim Chase python.list at tim.thechases.com
Sat Feb 16 16:14:18 EST 2008


> OP stated requirements were to move all the files into a single
> folder. Copytree will preserve the directory structure from the source
> side of the copy operation.

well, it would be "copying [not moving] files through Python",
but if the desire is to flatten the tree into a single directory,
that's also easy enough:

  import os, shutil
  source_dir = '/home/username/source/'
  dest_dir = '/home/username/dest/'
  for path, dirs, files in os.walk(source_dir):
    for fname in files:
      shutil.copy(os.path.join(path, fname), dest_dir)

The above doesn't do any sort of collision-testing, so if more
than one file in source_dir has the same name, the last one to be
copied wins, and the first one gets obliterated.  Caveat Coder.

-tkc






More information about the Python-list mailing list