设为首页 加入收藏

TOP

python中shutil和shutil库的用法
2023-07-23 13:42:52 】 浏览:14
Tags:python shutil

一、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')
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Django笔记十九之manager用法介绍 下一篇Python中的args和kwargs

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目