How to shutil.copyfile only if file differ? [duplicate]
Asked Answered
C

1

9

shutil.copyfile is quite useful for copying files from a location to another. Unfortunately, it does copy the file even though it already exists.

I find rsync --checksum quite convenient in this case, but I don't think it worth calling rsync from Python.

What alternative can I use to copy a file only if it does not exist or it is not the same?

Chummy answered 24/4, 2016 at 9:7 Comment(0)
L
17

You can use the following code:

import os
import filecmp
import shutil

if not os.path.exists(dst) or not filecmp.cmp(src, dst):
    shutil.copyfile(src, dst)
Livvy answered 24/4, 2016 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.