Menu

1 / 2

Python's `shutil`

DEV Community·MEROLINE LIZLENT·6 months ago
#pu6giwDk
#copying#python#beginners#developer#shutil
Reading 0:00
15s threshold

When you want to manipulate files and directories in Python you typically grab os . However, if your goal isn't manipulating file paths, then it's time to use shutil (shell utilities). Copying, moving, archiving and disk usage are all done through a very high level API.

Let's go through everything it can do.

Why shutil Over os ?

os provides you primitives : os.rename() , os.remove() os.mkdir() . These work, but they don't work with trees, they don't copy file meta data, they don't compress anything.

shutil works at a higher level - directories, archives, full file trees - and it comes in the standard library. No need to install.

import shutil

Enter fullscreen mode

Exit fullscreen mode

Copying Files

shutil.copy() — Content + Permissions

import shutil

# Copies file content and permissions (not metadata like timestamps) shutil . copy ( " source.txt " , " destination.txt " )

# Can also copy into a directory shutil .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.