wiltomap
wiltomap

Reputation: 4243

Python copy file ignoring tree structure

I need to copy files from a directory and its subdirectories to a unique destination directory, whitout reproducing the tree structure of the source directory (this means mixing together the files).

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import os
import shutil

src  = '/Users/wiltomap/Desktop/depart/paquet'
dest = '/Users/wiltomap/Desktop/arrivee'

for dir, subdir, files in os.walk(src):
    for f in files:
        shutil.copy(f, dest)

...and the code doesn't work! Here is the message I get by running it in Terminal:

IOError: [Errno 2] No such file or directory: 'paquet1.rtf'

'paquet1.rtf' is a file existing in subdirectory '/paquet/paquet1/'.

Thanks for help!

Upvotes: 0

Views: 67

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 881705

So maybe something like...:

for dir, subdir, files in os.walk(src):
    for f in files:
        targ = os.path.join(dest, f)
        if os.path.exists(targ):
            for i in itertools.count():
                targ = os.path.join(dest, '%s(%s)' % (f, i))
                if not os.path.exists(targ):
                    break
        shutil.copy(os.path.join(dir, f), targ)

Upvotes: 1

Related Questions