How to copy files preserving their metadata?

Asked

Viewed 447 times

0

I am making a script that identifies the changed files in two folders and then copies (if changed on 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 they don’t copy the date/time of modification what makes the same files always appear when I run the script.

Someone knows how to help me?

1 answer

1

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

shutil.copy2( src, dst, * , follow_symlinks=True )

Identical to copy() except that copy2() also Attempts to preserve all file Metadata.

copy2() you use copystat() to copy the file Metadata. Please see copystat() for more information about Platform support for modifying Symbolic link Metadata.

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

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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.