Вопрос

So I want to copy some files and directories from one location to another. Easy enough with shutil.move, but I run into problems when the files or directories are already in the destination. The error I get is Destination path '...' already exists.

I tried os.rename and it didn't produce the desired results either. Is there an easy way to copy files and dir structure to another location, even if those files and dir structure are already present in dest?

Here's what I have now:

fileList = os.listdir('/Users/john.leschinski/Desktop/testSrc')  
dest = '/Users/john.leschinski/Desktop/testMove'  
for i in fileList:  
    src = '/Users/john.leschinski/Desktop/testSrc/' + i  
    shutil.move(src,dest)
Это было полезно?

Решение

How about:

def move_over(src_dir, dest_dir):
    fileList = os.listdir(src_dir)
    for i in fileList:
        src = os.path.join(src_dir, i)
        dest = os.path.join(dest_dir, i)
        if os.path.exists(dest):
            if os.path.isdir(dest):
                move_over(src, dest)
                continue
            else:
                os.remove(dest)
        shutil.move(src, dest_dir)

src_dir = '/Users/john.leschinski/Desktop/testSrc'
dest_dir = '/Users/john.leschinski/Desktop/testMove'
move_over(src_dir, dest_dir)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top