Question

I want to copy all files from 2 directories to another, but when the files have the same name they get copied once(by one dir. not both) in the destination directory.

Here is the code:

def cp_files_tmp(src, dest):#copy dir's files into a  dir
    src_files = os.listdir(src)
    for file_name in src_files:
        full_file_name = os.path.join(src, file_name)
        if (os.path.isfile(full_file_name)):
            shutil.copy(full_file_name, dest)

dest = 'C:/temp/'
src_A= 'C:/sil/in/'     
src_B= 'C:/olw/in/'

cp_files_tmp(src_A, dest) # cp files
cp_files_tmp(src_B, dest) # cp files
Était-ce utile?

La solution

But what is an expected behaviour? If two files have the same name, then copying them simply overwrites the first one with the second, and there is no way it ends up differenly. You have to propose some kind of names unification, for example, if a file X exists, then copy the second X as X.tmp or something like this.

def cp_files_tmp(src, dest):
    src_files = os.listdir(src)
    for file_name in src_files:
        full_file_name = os.path.join(src, file_name)
        full_destination=os.path.join(dest,file_name)
        if (os.path.isfile(full_file_name)):
            while os.path.exists(full_destination):
                full_destination += ".duplicate"
            shutil.copy(full_file_name, full_destination)

dest = 'C:/temp/'
src_A= 'C:/sil/in/'     
src_B= 'C:/olw/in/'

cp_files_tmp(src_A, dest) # cp files
cp_files_tmp(src_B, dest) # cp files

This should result in files being copied from C:/sil/in and C:/olw/in to C:/temp and in case of duplicates it simply changes the resulting name to FILE_NAME.duplicate

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top