How to copy files preserving your metadata?

0

I am making a script that identifies the changed files in two folders and then copies (if changed on the modification date) from one to another, synchronization.

To copy the files already tried to use:

shutil.copy() 
shutil.copy2() 
shutil.copystat()

They copy the files, but do not copy the modification date / time , which causes the same files to always appear when I run the script.

Does anyone know how to help me?

    
asked by anonymous 30.06.2018 / 14:00

1 answer

1

shutil.copy2() is perfectly capable of copying the metadata containing the date and time of the last modification of the file:

  

     

Identical to copy() except that copy2() also attempts to preserve all   file metadata.

     

copy2() uses copystat() to copy the file metadata. Please see    copystat() for more information about platform support for modifying   symbolic link metadata.

Follows a code that ensures that the source will be copied to the destination together with all possible metadata. If the destination has a creation date older than the source, the destination will be overwritten with the source:

import shutil
import os

def sincronizar( src, dst ):

    # Verifica se origem existe
    if not os.path.exists( src ):
        return -1; # Erro

    # Copia se o arquivo de destino
    # nao existir
    if not os.path.exists( dst ):
        shutil.copy2( src, dst )
        return 1; # Sucesso

    # Recupera metadados da origem e do destino
    dst_info = os.stat(dst)
    src_info = os.stat(src)

    # Copia somente se a data de modificao do arquivo
    # de destino estiver mais antiga que 1 segundo
    if( src_info.st_mtime - dst_info.st_mtime > 1 ):
        shutil.copy2( src, dst )
        return 1 # Sucesso

    return 0 # Sucesso (sem copia)
    
30.06.2018 / 15:12