一、shutil目录和文件操作

Python shutil库提供了对文件和目录复制、移动、删除、压缩、解压等操作。

1. 复制文件或目录

  • shutil.copy(src, dst):复制文件或目录
  • shutil.copyfile(src, dst):复制文件,src和dst只能是文件
  • shutil.copytree(src, dst, dirs_exist_ok=False):复制目录,默认dst目录不存在,否则会报错。

示例:

import osimport shutildirpath    = os.path.dirname(os.path.realpath(__file__))sourcedir  = os.path.join(dirpath, "shutil_a")sourcefile = os.path.join(dirpath, "shutil_a", "test.txt")        destdir    = os.path.join(dirpath, "shutil_b")destfile   = os.path.join(dirpath, "shutil_b", "test2.txt")# 复制文件或目录shutil.copy(sourcefile, destdir)        # 复制文件shutil.copyfile(sourcefile, destfile) # 复制目录shutil.copytree(sourcedir, destfile, dirs_exist_ok=True) 

2. 移动文件或目录

语法:shutil.move(src, dst)

示例:

import osimport shutildirpath    = os.path.dirname(os.path.realpath(__file__))sourcedir  = os.path.join(dirpath, "shutil_a")sourcefile = os.path.join(dirpath, "shutil_a", "test.txt")        destdir    = os.path.join(dirpath, "shutil_b")shutil.move(sourcefile, destdir)shutil.move(destdir, sourcedir)

3. 删除文件和目录

删除某个文件使用 os 模块提供的remove和unlink方法:

  • os.remove(path)
  • os.unlink(path)

删除目录使用 shutil.rmtree 方法:

import osimport shutildirpath    = os.path.dirname(os.path.realpath(__file__))     destdir    = os.path.join(dirpath, "shutil_b")shutil.rmtree(destdir)

二、shutil文件压缩、解压

shutil库也支持文件压缩、解压操作,这个功能在Python 3.2版本引入。

1. 压缩文件

语法格式:

shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])
  • base_name:压缩包文件名
  • format:压缩包格式,支持zip,tar,bztar,gztar,xztar格式,可使用shutil.get_archive_formats()方法查看
  • root_dir:要压缩文件路径的根目录(默认当前目录)
  • base_dir:相对于root_dir的压缩文件路径(默认当前目录)

示例:

import osimport shutil#Python小白学习交流群:725638078dirpath    = os.path.dirname(os.path.realpath(__file__))archive_name  = os.path.join(dirpath, "shutil_a")root_dir = archive_nameshutil.make_archive(archive_name, 'zip', root_dir)

2. 解压文件

语法格式:

shutil.unpack_archive(filename[, extract_dir[, format]])

示例:

import osimport shutildirpath      = os.path.dirname(os.path.realpath(__file__))archive_name = os.path.join(dirpath, "shutil_a.zip")extract_dir  = os.path.join(dirpath, "shutil_a")   shutil.unpack_archive(archive_name, extract_dir, 'zip')