Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
import shutilCopy 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" > testshutil.copy2("test", "abc")'abc'!cat abctesting
shutil.copytree¶
https://
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)