Master Python’s shutil: Copy, Move, Delete & Archive Files with Ease
This article introduces Python’s shutil module, explains its purpose as a shell utility supplement to os, and provides detailed examples of its key functions—including copyfileobj, copy, copy2, copytree, rmtree, move, and make_archive—complete with code snippets and usage tips.
What is shutil
shutil can be understood as sh + util, meaning a shell utility. The shutil module supplements the os module, mainly for copying, deleting, moving, compressing, and extracting files.
Key Methods of shutil
shutil.copyfileobj(fsrc, fdst[, length=16*1024])
Copies file contents to another file, optionally specifying the size. This method is the basis for other copy functions.
def copyfileobj(fsrc, fdst, length=16*1024):
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)Note: fsrc and fdst must be file objects opened with open().
import shutil
s = open('fsrc.txt','r')
d = open('fdst.txt','w')
shutil.copyfileobj(s, d, length=16*1024)shutil.copyfile(src, dst)
Copies a file.
shutil.copyfile('f1.log', 'f2.log') # destination file need not existshutil.copymode(src, dst)
Copies only the permission bits; content, group, and user remain unchanged.
shutil.copymode('f1.log', 'f2.log') # destination must existshutil.copystat(src, dst)
Copies status information such as mode bits, atime, mtime, and flags.
shutil.copystat('f1.log', 'f2.log') # destination must existshutil.copy(src, dst)
Copies a file along with its permissions.
import shutil
shutil.copy('f1.log', 'f2.log')shutil.copy2(src, dst)
Copies a file and its metadata.
import shutil
shutil.copy2('f1.log', 'f2.log')shutil.copytree(src, dst, symlinks=False, ignore=None)
Recursively copies an entire directory tree.
src: source directory
dst: destination directory (created automatically; must not already exist)
symlinks: whether to copy symbolic links (True) or ignore them (False, default)
ignore: pattern(s) to ignore, e.g., ignore_patterns() copy_function: function used to copy files, default is copy2 (Python 3 added)
ignore_dangling_symlinks: if False, copying a broken symlink raises an error; set True to ignore.
import shutil, os
folder1 = os.path.join(os.getcwd(), "aaa")
folder2 = os.path.join(os.getcwd(), "bbb", "ccc")
shutil.copytree(folder1, folder2, ignore=shutil.ignore_patterns("abc.txt", "bcd.txt"))shutil.rmtree(path[, ignore_errors[, onerror]])
Recursively deletes a directory tree.
import shutil
shutil.rmtree('folder1')shutil.move(src, dst)
Recursively moves a file or directory, similar to the Unix mv command.
import shutil
shutil.move('folder1', 'folder3')shutil.make_archive(base_name, format[, root_dir[, base_dir, ...]])
Creates an archive (e.g., zip, tar) and returns its file path.
base_name: name or path of the archive
format: archive type such as "zip", "tar", "bztar", "gztar"
root_dir: directory to archive (default current directory)
base_dir: directory within the archive
owner, group: user and group for the archive (default current)
logger: logging.Logger instance for logging
import shutil
shutil.make_archive('copy', 'zip')Conclusion
This article introduced Python’s shutil module and detailed its main functions, providing code examples and explanations to help readers understand and apply file operations in real projects.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
