python中shutil和shutil库的用法

举报
python教程 发表于 2023/04/18 15:57:50 2023/04/18
【摘要】 一、shutil目录和文件操作Python shutil库提供了对文件和目录复制、移动、删除、压缩、解压等操作。 1. 复制文件或目录shutil.copy(src, dst):复制文件或目录shutil.copyfile(src, dst):复制文件,src和dst只能是文件shutil.copytree(src, dst, dirs_exist_ok=False):复制目录,默认dst...

一、shutil目录和文件操作

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

1. 复制文件或目录

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

示例:

import os
import shutil

dirpath    = 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 os
import shutil

dirpath    = 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 os
import shutil

dirpath    = 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 os
import shutil
#Python小白学习交流群:725638078
dirpath    = os.path.dirname(os.path.realpath(__file__))
archive_name  = os.path.join(dirpath, "shutil_a")
root_dir = archive_name
shutil.make_archive(archive_name, 'zip', root_dir)

2. 解压文件

语法格式:

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

示例:

import os
import shutil

dirpath      = 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')
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。