+3 votes
in Programming Languages by (54.6k points)
Which Python function should I use to copy data from one file to another? The function should also preserve the file metadata.

1 Answer

+2 votes
by (347k points)
selected by
 
Best answer

You can use the copy2() function of shutil module. This function is identical to copy() except that copy2() also attempts to preserve file metadata. It uses copystat() to copy the file metadata.

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

When follow_symlinks is false, and src is a symbolic link, copy2() attempts to copy all metadata from the src symbolic link to the newly-created dst symbolic link. However, this functionality is not available on all platforms. On platforms where some or all of this functionality is unavailable, copy2() will preserve all the metadata it can; copy2() never raises an exception because it cannot preserve file metadata.

Here is an example:

import shutil
shutil.copy2("src_file", "dst_file")


...