Ben Chuanlong Du's Blog

It is never too late to learn.

Hands on the Python module shutil

In [1]:
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.

In [2]:
!touch abc
In [3]:
!echo "testing" > test
In [4]:
shutil.copy2("test", "abc")
Out[4]:
'abc'
In [5]:
!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.

In [1]:
!rm -rf test1 && mkdir -p test1 && touch test1/1.txt && ls test1/
1.txt
In [2]:
!rm -rf test2 && mkdir -p test2 && touch test2/2.txt && ls test2/
2.txt
In [4]:
shutil.copytree("test1/", "test2/", dirs_exist_ok=True)
Out[4]:
'test2/'
In [5]:
!ls test2/
1.txt  2.txt

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

In [ ]:
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)

Comments