1

I built a script in Python to copy any files from a list of folders to a destination folder already made.

source = ['c:/test/source/', ]
destination = 'c:/test/destination/'

def copy(source, destination):

    import os, shutil

    try:
        for folder in source:
            files = os.listdir(folder)

            for file in files:
                current_file = os.path.join(folder, file)
                shutil.copy(os.path.join(folder, file), destination)

    except:
         pass

The problem with this script is that it didn't copy the sub folders. Any suggestion to fix it ?

Thanks

0

1 Answer 1

2

I think you need to use shutil.copytree

shutil.copytree(os.path.join(folder, file), destination)

but shutil.copytree won't overwrite if folder exist, if you want to overwrite all, use distutils.dir_util.copy_tree

from distutils import dir_util
dir_util.copy_tree(os.path.join(folder, file), destination)
Sign up to request clarification or add additional context in comments.

6 Comments

Yes it is almost working, but still another problem. Indeed the script told me that there already is a folder named 'destination'. What I want is to force the copy of folders, files and subfolders if they already exists.
Yes it overrides all files. But ther is a last issue ! :) The sub folder is not created... And so I have this kind of error : distutils.errors.DistutilsFileError: could not create 'c:/test/destination\Nouveau dossier\Nouveau document texte (2).txt': No such file or directory
I have to create myself the sub folder to get it work. Any solution ?
what do you mean the sub folder ? for example if you have folder name1 and you what to copy the folder name1 to folder name2 but you don't have the name2 folder it will create it, but if you don't have name1 it will raise DistutilsFileError you need to have name1 folder
In the source folder, I have files and others folders which contains other files and other folders maybe. So I want to copy everything in a destination folder. However if I have 'c:/test/source/subfolder/file.txt' and if my destination folder exists but is empty, so there is an error.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.