How to copy file in Python

edit  Updated by

The shutil package has many methods we can use to copy/move files:

1. Copy file using copyfile from shutil

from shutil import copyfile
copyfile(src, dst)

2. Copy file/folder using copy from shutil

from shutil import copy
copy(src, dst)
notificationNote
The difference between copy and copyfile is that in copy(src, dst) the dst can be a directory

3. Copy file/folder using copy2 from shutil

from shutil import copy2
copy2(src, dst)

copy2(src,dst) is often more useful than copyfile(src,dst) because:

4. Conclusion

The below table shows the functions for copying/moving file/folder

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     Function     β”‚ Copies β”‚   Copies  β”‚Can useβ”‚   Destination  β”‚
β”‚                  β”‚metadataβ”‚permissionsβ”‚buffer β”‚may be directoryβ”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚shutil.copy       β”‚   No   β”‚    Yes    β”‚   No  β”‚      Yes       β”‚
β”‚shutil.copyfile   β”‚   No   β”‚     No    β”‚   No  β”‚       No       β”‚
β”‚shutil.copy2      β”‚  Yes   β”‚    Yes    β”‚   No  β”‚      Yes       β”‚
β”‚shutil.copyfileobjβ”‚   No   β”‚     No    β”‚  Yes  β”‚       No       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜