Fundamentals 7 min read

Using Python's shutil Module for File and Directory Operations

This article introduces Python's built‑in shutil module, explains its key functions for copying, moving, deleting, archiving, and retrieving file information, and provides comprehensive code examples demonstrating how to prepare test files and perform common file‑system tasks such as copying files, moving directories, and creating archives.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using Python's shutil Module for File and Directory Operations

In daily script development and system administration, file and directory operations such as copying, moving, and compressing are common. Python's shutil module offers high‑level interfaces that simplify these tasks.

shutil is a standard library module that extends os and os.path with functions for copying, archiving, and compressing files and directories.

Commonly used functions include:

Copy files: copy() , copy2() , copyfile() , copymode()

Copy directories: copytree()

Move files: move()

Delete directories: rmtree()

Create archives: make_archive()

Extract archives: unpack_archive()

Get terminal size: get_terminal_size()

Example environment preparation

import os
import shutil
# 创建测试目录
test_dir = 'test_shutil'
os.makedirs(test_dir, exist_ok=True)
# 在测试目录下创建一个子目录
sub_dir = os.path.join(test_dir, 'sub_dir')
os.makedirs(sub_dir, exist_ok=True)
# 创建一个测试文件
with open(os.path.join(test_dir, 'test.txt'), 'w') as f:
    f.write('这是一个测试文件')
# 创建另一个测试文件
with open(os.path.join(sub_dir, 'test_sub.txt'), 'w') as f:
    f.write('这是子目录下的测试文件')

Example 1: Copy a file

import shutil
源文件 = os.path.join(test_dir, 'test.txt')
目标文件 = os.path.join(test_dir, 'test_copy.txt')
# 复制文件
shutil.copy(源文件, 目标文件)
# 输出确认
print(f"已复制文件: {源文件} -> {目标文件}")

Example 2: Move a file

import shutil
源文件 = os.path.join(test_dir, 'test_copy.txt')
目标路径 = sub_dir
# 移动文件
shutil.move(源文件, 目标路径)
# 输出确认
print(f"已移动文件: {源文件} -> {目标路径}")

Example 3: Copy a directory

import shutil
源目录 = test_dir
目标目录 = 'test_shutil_copy'
# 复制目录
shutil.copytree(源目录, 目标目录)
# 输出确认
print(f"已复制目录: {源目录} -> {目标目录}")

Example 4: Delete a directory

import shutil
目录路径 = 'test_shutil_copy'
# 删除目录
shutil.rmtree(目录路径)
print(f"已删除目录: {目录路径}")

Example 5: Create an archive

import shutil
源目录 = test_dir
归档文件 = 'archive.zip'
# 创建归档文件
shutil.make_archive('archive', 'zip', 源目录)
print(f"已创建归档文件: {归档文件}")

Example 6: Extract an archive

import shutil
归档文件 = 'archive.zip'
解压目录 = 'unarchived'
# 解压文件
shutil.unpack_archive(归档文件, 解压目录)
print(f"已解压文件: {归档文件} -> {解压目录}")

Example 7: Get terminal size

import shutil
# 获取终端窗口大小
宽度, 高度 = shutil.get_terminal_size()
print(f"终端宽度: {宽度}, 终端高度: {高度}")

Example 8: Recursive copy of a directory

import shutil
源目录 = test_dir
目标目录 = 'test_shutil_copy'
# 递归复制文件
shutil.copytree(源目录, 目标目录)
print(f"已递归复制目录: {源目录} -> {目标_directory}")

Example 9: Copy a file while preserving metadata

import shutil
源文件 = os.path.join(test_dir, 'test.txt')
目标文件 = os.path.join(test_dir, 'test_copy2.txt')
# 复制文件并保留元数据
shutil.copy2(源文件, 目标文件)
print(f"已复制文件并保留元数据: {源文件} -> {目标文件}")

Example 10: Copy file permission mode

import shutil
源文件 = os.path.join(test_dir, 'test.txt')
目标文件 = os.path.join(test_dir, 'test_copy3.txt')
# 创建目标文件
with open(目标文件, 'w'):
    pass
# 复制文件权限模式
shutil.copymode(源文件, 目标_file)
print(f"已复制文件权限模式: {源文件} -> {目标_file}")
archiveCopyshutilfile operationsMove
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.