Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

import shutil

Copy Files

copy2 is the preferred function to copy files as it is more flexible (than copy) and also preserve file metadata (compared to copyfile).

copyfileobj

shutil.copy2 siliently overwrite the destination file if it already exists, which is consistent with the behavior of the cpcomamnd in Linux/Unix.

!touch abc
!echo "testing" > test
shutil.copy2("test", "abc")
'abc'
!cat abc
testing

shutil.copytree

https://docs.python.org/3/library/shutil.html#shutil.copytree

shutil.copytree copies the content of the source directory to the destination directory.

!rm -rf test1 && mkdir -p test1 && touch test1/1.txt && ls test1/
1.txt
!rm -rf test2 && mkdir -p test2 && touch test2/2.txt && ls test2/
2.txt
shutil.copytree("test1/", "test2/", dirs_exist_ok=True)
'test2/'
!ls test2/
1.txt  2.txt

Below is an example of copying ~/.ssh to another location /tmp/ssh but skipping sockets.

def _ignore_socket(dir_, files):
    dir_ = Path(dir_)
    return [file for file in files if (dir_ / file).is_socket()]


shutil.copytree(Path.home() / ".ssh", "/tmp/ssh", ignore=_ignore_socket)