13Python标准库系列之shutil模块

简介:

Python标准库系列之shutil模块


The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal. For operations on individual files, see also the os module.


对文件、文件夹、压缩包进行处理的模块。

官方文档:https://docs.python.org/3.5/library/shutil.html

文件和目录操作

shutil.copyfileobj(fsrc, fdst[, length])

将文件内容拷贝到另一个文件中

1
2
3
4
5
6
7
8
9
>>>  import  shutil
# 循环读取old.txt文件内容并写入到new.txt文件当中
>>> shutil.copyfileobj( open ( 'old.txt' , 'r' ),  open ( 'new.txt' 'w' ))
>>>  import  os
# 查看复制过去的文件内容
>>> os.system( "cat old.txt new.txt"
old
old
0

shutil.copyfile(src, dst, *, follow_symlinks=True)

拷贝整个文件,没有第二个文件就创建,有就覆盖

1
2
3
4
5
6
7
8
9
10
>>> os.system( "cat old.txt new.txt" )
old
new
0
>>> shutil.copyfile( 'old.txt' 'new.txt' )
# 把第二个文件内容给覆盖了
>>> os.system( "cat old.txt new.txt" )     
old
old
0

shutil.copymode(src, dst, *, follow_symlinks=True)

仅拷贝文件权限,文件的内容、组、用户均不变

1
2
3
4
5
6
7
8
9
10
>>> os.system( "ls -l old.txt new.txt" )    
- rw - rw - rw -  1  ansheng ansheng  4  5 月   26  15 : 54  new.txt
- rw - rw - r - -  1  ansheng ansheng  4  5 月   26  15 : 52  old.txt
0
>>> shutil.copymode( 'old.txt' 'new.txt' )
# 文件权限都变成644了
>>> os.system( "ls -l old.txt new.txt" )   
- rw - rw - r - -  1  ansheng ansheng  4  5 月   26  15 : 54  new.txt
- rw - rw - r - -  1  ansheng ansheng  4  5 月   26  15 : 52  old.txt
0

shutil.copystat(src, dst, *, follow_symlinks=True)

拷贝文件状态的信息,文件必须存在,不copy改动时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
>>> os.system( "stat old.txt new.txt" )  
   文件: 'old.txt'
   大小: 4                块: 8           IO 块: 4096    普通文件
设备: 801h / 2049d         Inode: 1835014      硬链接: 1
权限:( 0664 / - rw - rw - r - - )  Uid:(  1000 /  ansheng)   Gid:(  1000 /  ansheng)
最近访问: 2016 - 05 - 26  15 : 53 : 09.813612241  + 0800
最近更改: 2016 - 05 - 26  15 : 52 : 54.830640166  + 0800
最近改动: 2016 - 05 - 26  15 : 52 : 54.830640166  + 0800
创建时间: -
   文件: 'new.txt'
   大小: 4                块: 8           IO 块: 4096    普通文件
设备: 801h / 2049d         Inode: 1835024      硬链接: 1
权限:( 0664 / - rw - rw - r - - )  Uid:(  1000 /  ansheng)   Gid:(  1000 /  ansheng)
最近访问: 2016 - 05 - 26  15 : 56 : 22.540041783  + 0800
最近更改: 2016 - 05 - 26  15 : 54 : 24.244922722  + 0800
最近改动: 2016 - 05 - 26  15 : 55 : 38.353967649  + 0800
创建时间: -
0
>>> shutil.copystat( 'old.txt' 'new.txt' )
>>> os.system( "stat old.txt new.txt" )    
   文件: 'old.txt'
   大小: 4                块: 8           IO 块: 4096    普通文件
设备: 801h / 2049d         Inode: 1835014      硬链接: 1
权限:( 0664 / - rw - rw - r - - )  Uid:(  1000 /  ansheng)   Gid:(  1000 /  ansheng)
最近访问: 2016 - 05 - 26  15 : 53 : 09.813612241  + 0800
最近更改: 2016 - 05 - 26  15 : 52 : 54.830640166  + 0800
最近改动: 2016 - 05 - 26  15 : 52 : 54.830640166  + 0800
创建时间: -
   文件: 'new.txt'
   大小: 4                块: 8           IO 块: 4096    普通文件
设备: 801h / 2049d         Inode: 1835024      硬链接: 1
权限:( 0664 / - rw - rw - r - - )  Uid:(  1000 /  ansheng)   Gid:(  1000 /  ansheng)
最近访问: 2016 - 05 - 26  15 : 53 : 09.813612000  + 0800
最近更改: 2016 - 05 - 26  15 : 52 : 54.830640000  + 0800
最近改动: 2016 - 05 - 26  15 : 56 : 48.765143115  + 0800
创建时间: -
0

shutil.copy(src, dst, *, follow_symlinks=True)

拷贝文件和状态信息,同样不copy改动时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
>>> os.system( "stat old.txt new.txt" )  
   文件: 'old.txt'
   大小: 4                块: 8           IO 块: 4096    普通文件
设备: 801h / 2049d         Inode: 1835014      硬链接: 1
权限:( 0664 / - rw - rw - r - - )  Uid:(  1000 /  ansheng)   Gid:(  1000 /  ansheng)
最近访问: 2016 - 05 - 26  15 : 53 : 09.813612241  + 0800
最近更改: 2016 - 05 - 26  15 : 52 : 54.830640166  + 0800
最近改动: 2016 - 05 - 26  15 : 52 : 54.830640166  + 0800
创建时间: -
   文件: 'new.txt'
   大小: 0                块: 0           IO 块: 4096    普通空文件
设备: 801h / 2049d         Inode: 1835023      硬链接: 1
权限:( 0664 / - rw - rw - r - - )  Uid:(  1000 /  ansheng)   Gid:(  1000 /  ansheng)
最近访问: 2016 - 05 - 26  15 : 57 : 53.448632439  + 0800
最近更改: 2016 - 05 - 26  15 : 57 : 53.448632439  + 0800
最近改动: 2016 - 05 - 26  15 : 57 : 53.448632439  + 0800
创建时间: -
0
>>> shutil.copy2( 'old.txt' 'new.txt' )
>>> os.system( "stat old.txt new.txt" )  
   文件: 'old.txt'
   大小: 4                块: 8           IO 块: 4096    普通文件
设备: 801h / 2049d         Inode: 1835014      硬链接: 1
权限:( 0664 / - rw - rw - r - - )  Uid:(  1000 /  ansheng)   Gid:(  1000 /  ansheng)
最近访问: 2016 - 05 - 26  15 : 53 : 09.813612241  + 0800
最近更改: 2016 - 05 - 26  15 : 52 : 54.830640166  + 0800
最近改动: 2016 - 05 - 26  15 : 52 : 54.830640166  + 0800
创建时间: -
   文件: 'new.txt'
   大小: 4                块: 8           IO 块: 4096    普通文件
设备: 801h / 2049d         Inode: 1835023      硬链接: 1
权限:( 0664 / - rw - rw - r - - )  Uid:(  1000 /  ansheng)   Gid:(  1000 /  ansheng)
最近访问: 2016 - 05 - 26  15 : 53 : 09.813612000  + 0800
最近更改: 2016 - 05 - 26  15 : 52 : 54.830640000  + 0800
最近改动: 2016 - 05 - 26  15 : 58 : 07.938760974  + 0800
创建时间: -
0

shutil.ignore_patterns(*patterns)

This factory function creates a function that can be used as a callable for copytree()‘s ignore argument, ignoring files and directories that match one of the glob-style patterns provided. See the example below.

shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)

递归的去拷贝文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>> os.system( "tree folder1" )
folder1
├──  dir
├──  file .txt
├── sc.pyc
├── tmp
└── vgauthsvclog.txt. 0  - / tmp / vgauthsvclog.txt. 0
2  directories,  3  files
0
# folder2目录必须不存在,symlinks=True只copy链接文件,如果等于False就copy源文件,ignore等于不copy的文件或者目录
>>> shutil.copytree( 'folder1' 'folder2' , symlinks = False , ignore = shutil.ignore_patterns( '*.pyc' 'tmp*' ))   
>>> os.system( "tree folder2" )
folder2
├──  dir
├──  file .txt
└── vgauthsvclog.txt. 0
1  directory,  2  files
0

shutil.rmtree(path, ignore_errors=False, onerror=None)

递归的去删除文件

1
2
3
4
5
6
7
>>> os.system( "ls -d folder2" )
folder2
0
>>> shutil.rmtree( 'folder2' )
>>> os.system( "ls -d folder2" )
ls: 无法访问 'folder2' : 没有那个文件或目录
512

shutil.move(src, dst, copy_function=copy2)

递归的去移动文件,它类似mv命令,其实就是重命名。

1
2
3
4
5
6
7
8
9
10
>>> os.system( "ls -ld folder1" )
drwxrwxr - 4  ansheng ansheng  4096  5 月   26  16 : 09  folder1
0
>>> shutil.move( 'folder1' 'folder3' )
>>> os.system( "ls -ld folder1" )      
ls: 无法访问 'folder1' : 没有那个文件或目录
512
>>> os.system( "ls -ld folder3" )
drwxrwxr - 4  ansheng ansheng  4096  5 月   26  16 : 09  folder3
0

shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])

Create an archive file (such as zip or tar) and return its name.

1
2
3
4
5
6
7
8
9
10
>>> os.system( "ls -dl folder3" )
drwxrwxr - 4  ansheng ansheng  4096  5 月   26  16 : 21  folder3
0
# /home/ansheng/folder3是保存的文件,gztar是后缀名,/home/ansheng/folder3是要打包的路径
>>> shutil.make_archive( "/home/ansheng/folder3" 'gztar' , root_dir = '/home/ansheng/folder3' )
# 返回文件打包放在那儿了
'/home/ansheng/folder3.tar.gz'
>>> os.system( "ls -dl /home/ansheng/folder3.tar.gz" )
- rw - rw - r - -  1  ansheng ansheng  263  5 月   26  16 : 22  / home / ansheng / folder3.tar.gz
0

可选参数如下:

参数 说明
base_name 压缩包的文件名,也可以是压缩包的路径。
format 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
root_dir 要压缩的文件夹路径(默认当前目录)
owner 用户,默认当前用户
group 组,默认当前组

shutil对压缩包的处理是调用ZipFile和TarFile两个模块来进行的,后面会介绍这两个模块的使用方法。











本文转自 Edenwy  51CTO博客,原文链接:http://blog.51cto.com/edeny/1925762,如需转载请自行联系原作者
目录
相关文章
|
4月前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
610 7
|
4月前
|
监控 安全 程序员
Python日志模块配置:从print到logging的优雅升级指南
从 `print` 到 `logging` 是 Python 开发的必经之路。`print` 调试简单却难维护,日志混乱、无法分级、缺乏上下文;而 `logging` 支持级别控制、多输出、结构化记录,助力项目可维护性升级。本文详解痛点、优势、迁移方案与最佳实践,助你构建专业日志系统,让程序“有记忆”。
410 0
|
4月前
|
数据可视化 关系型数据库 MySQL
【可视化大屏】全流程讲解用python的pyecharts库实现拖拽可视化大屏的背后原理,简单粗暴!
本文详解基于Python的电影TOP250数据可视化大屏开发全流程,涵盖爬虫、数据存储、分析及可视化。使用requests+BeautifulSoup爬取数据,pandas存入MySQL,pyecharts实现柱状图、饼图、词云图、散点图等多种图表,并通过Page组件拖拽布局组合成大屏,支持多种主题切换,附完整源码与视频讲解。
447 4
【可视化大屏】全流程讲解用python的pyecharts库实现拖拽可视化大屏的背后原理,简单粗暴!
|
4月前
|
传感器 运维 前端开发
Python离群值检测实战:使用distfit库实现基于分布拟合的异常检测
本文解析异常(anomaly)与新颖性(novelty)检测的本质差异,结合distfit库演示基于概率密度拟合的单变量无监督异常检测方法,涵盖全局、上下文与集体离群值识别,助力构建高可解释性模型。
455 10
Python离群值检测实战:使用distfit库实现基于分布拟合的异常检测
|
4月前
|
JSON 算法 API
Python中的json模块:从基础到进阶的实用指南
本文深入解析Python内置json模块的使用,涵盖序列化与反序列化核心函数、参数配置、中文处理、自定义对象转换及异常处理,并介绍性能优化与第三方库扩展,助你高效实现JSON数据交互。(238字)
510 4
|
4月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
468 0
|
4月前
|
XML JSON 数据处理
超越JSON:Python结构化数据处理模块全解析
本文深入解析Python中12个核心数据处理模块,涵盖csv、pandas、pickle、shelve、struct、configparser、xml、numpy、array、sqlite3和msgpack,覆盖表格处理、序列化、配置管理、科学计算等六大场景,结合真实案例与决策树,助你高效应对各类数据挑战。(238字)
483 0
|
5月前
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
503 0
|
开发者 Python
如何在Python中管理模块和包的依赖关系?
在实际开发中,通常会结合多种方法来管理模块和包的依赖关系,以确保项目的顺利进行和可维护性。同时,要及时更新和解决依赖冲突等问题,以保证代码的稳定性和可靠性
623 159

推荐镜像

更多