翼度科技»论坛 编程开发 python 查看内容

python中shutil和shutil库的用法

7

主题

7

帖子

21

积分

新手上路

Rank: 1

积分
21
一、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')
复制代码
来源:https://www.cnblogs.com/xxpythonxx/p/17298705.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具