python中shutil和shutil库的用法

打印 上一主题 下一主题

主题 1845|帖子 1845|积分 5535

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
一、shutil目录和文件操作

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


  • shutil.copy(src, dst):复制文件或目录
  • shutil.copyfile(src, dst):复制文件,src和dst只能是文件
  • shutil.copytree(src, dst, dirs_exist_ok=False):复制目录,默认dst目录不存在,否则会报错。
示例:
  1. import os
  2. import shutil
  3. dirpath    = os.path.dirname(os.path.realpath(__file__))
  4. sourcedir  = os.path.join(dirpath, "shutil_a")
  5. sourcefile = os.path.join(dirpath, "shutil_a", "test.txt")        
  6. destdir    = os.path.join(dirpath, "shutil_b")
  7. destfile   = os.path.join(dirpath, "shutil_b", "test2.txt")
  8. # 复制文件或目录
  9. shutil.copy(sourcefile, destdir)        
  10. # 复制文件
  11. shutil.copyfile(sourcefile, destfile)
  12. # 复制目录
  13. shutil.copytree(sourcedir, destfile, dirs_exist_ok=True)
复制代码
2. 移动文件或目录

语法:shutil.move(src, dst)
示例:
  1. import os
  2. import shutil
  3. dirpath    = os.path.dirname(os.path.realpath(__file__))
  4. sourcedir  = os.path.join(dirpath, "shutil_a")
  5. sourcefile = os.path.join(dirpath, "shutil_a", "test.txt")        
  6. destdir    = os.path.join(dirpath, "shutil_b")
  7. shutil.move(sourcefile, destdir)
  8. shutil.move(destdir, sourcedir)
复制代码
3. 删除文件和目录

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

  • os.remove(path)
  • os.unlink(path)
删除目录使用 shutil.rmtree 方法:
  1. import os
  2. import shutil
  3. dirpath    = os.path.dirname(os.path.realpath(__file__))     
  4. destdir    = os.path.join(dirpath, "shutil_b")
  5. shutil.rmtree(destdir)
复制代码
二、shutil文件压缩、解压

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

语法格式:
  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的压缩文件路径(默认当前目录)
示例:
  1. import os
  2. import shutil
  3. #Python小白学习交流群:725638078
  4. dirpath    = os.path.dirname(os.path.realpath(__file__))
  5. archive_name  = os.path.join(dirpath, "shutil_a")
  6. root_dir = archive_name
  7. shutil.make_archive(archive_name, 'zip', root_dir)
复制代码
2. 解压文件

语法格式:
  1. shutil.unpack_archive(filename[, extract_dir[, format]])
复制代码
示例:
  1. import os
  2. import shutil
  3. dirpath      = os.path.dirname(os.path.realpath(__file__))
  4. archive_name = os.path.join(dirpath, "shutil_a.zip")
  5. extract_dir  = os.path.join(dirpath, "shutil_a")   
  6. shutil.unpack_archive(archive_name, extract_dir, 'zip')
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
继续阅读请点击广告
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

铁佛

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表