简介

shutil模块提供了大量的文件的高级操作。特别针对文件拷贝和删除,主要功能为目录和文件操作以及压缩操作。对单个文件的操作也可参见os模块。

注意即便是更高级别的文件复制函数(shutil.copy(),shutil.copy2())也不能复制所有文件的元数据。这意味着在POSIX平台上,文件的所有者和组以及访问控制列表都将丢失。在Mac OS中资源fork和其他元数据无法使用。这意味着资源将丢失,文件类型和创建者代码将不正确。在Windows上,文件所有者,ACL和备用数据流不会被复制。

  • 功能:高级文件操作。
  • 类型:标准模块
  • 相关模块:
    1. os 标准模块。
    2. zipfile 标准模块。
    3. tarfile 标准模块。

拷贝文件

shutil.copyfile(src, dst):复制文件内容(不包含元数据)从src到dst。 DST必须是完整的目标文件名;拷贝目录参见shutil.copy()。如果src和dst是同一文件,就会引发错误shutil.Error。dst必须是可写的,否则将引发异常IOError。如果dst已经存在,它会被替换。特殊文件,例如字符或块设备和管道不能使用此功能,因为copyfile会打开并阅读文件。 src和dst的是字符串形式的路径名。

from shutil import *
from glob import glob print 'BEFORE:', glob('shutil_copyfile.*')
copyfile('shutil_copyfile.py', 'shutil_copyfile.py.copy')
print 'AFTER:', glob('shutil_copyfile.*')

copyfile()调用了底函数层copyfileobj()。
shutil.copyfileobj(fsrc, fdst[, length]):复制文件内容(不包含元数据)从类文件对象src到类文件对dst。可选参数length指定缓冲区的大小,负数表示一次性读入。默认会把数据切分成小块拷贝,以免占用太多内存。注意:拷贝是从fsrc的当前文件开始。

from shutil import *
import os
from StringIO import StringIO
import sys class VerboseStringIO(StringIO):
def read(self, n=-1):
next = StringIO.read(self, n)
print 'read(%d) bytes' % n
return next lorem_ipsum = '''Lorem ipsum dolor sit amet, consectetuer adipiscing
elit. Vestibulum aliquam mollis dolor. Donec vulputate nunc ut diam.
Ut rutrum mi vel sem. Vestibulum ante ipsum.''' print 'Default:'
input = VerboseStringIO(lorem_ipsum)
output = StringIO()
copyfileobj(input, output) print() print 'All at once:'
input = VerboseStringIO(lorem_ipsum)
output = StringIO()
copyfileobj(input, output, -1) print() print 'Blocks of 256:'
input = VerboseStringIO(lorem_ipsum)
output = StringIO()
copyfileobj(input, output, 256)

shutil.copy(src, dst):复制文件src到文件或目录dst。如果dst是目录,使用src相同的文件名创建(或覆盖),权限位也会复制。src和dst的是字符串形式的路径名。

from shutil import *
import os os.mkdir('example')
print('BEFORE:', os.listdir('example'))
copy('shutil_copy.py', 'example')
print('AFTER:', os.listdir('example'))

shutil.copy2(src, dst):类似shutil.copy,元数据也复制,实际上先调用shutil.copy,然后使用copystat。这类似于Unix命令cp -p。

from shutil import *
import os
import time def show_file_info(filename):
stat_info = os.stat(filename)
print '\tMode :', stat_info.st_mode
print '\tCreated :', time.ctime(stat_info.st_ctime)
print '\tAccessed:', time.ctime(stat_info.st_atime)
print '\tModified:', time.ctime(stat_info.st_mtime) os.mkdir('example')
print('SOURCE:')
show_file_info('shutil_copy2.py')
copy2('shutil_copy2.py', 'example')
print('DEST:')
show_file_info('example/shutil_copy2.py')

shutil.ignore_patterns(*patterns) 为copytree的辅助函数,提供glob功能,示例:

from shutil import copytree, ignore_patterns

copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

拷贝文件元数据

当由UNIX下创建文件默认基于umask设置权限,copymode()可以复制权限。

shutil.copymode(src, dst):从SRC复制权限位到DST。该文件的内容,所有者和组不受影响。src和dst的是字符串形式的路径名。

from shutil import *
from commands import *
import os with open('file_to_change.txt', 'wt') as f:
f.write('content')
os.chmod('file_to_change.txt', 0444) print 'BEFORE:'
print getstatus('file_to_change.txt')
copymode('shutil_copymode.py', 'file_to_change.txt')
print 'AFTER :'
print getstatus('file_to_change.txt')

要想拷贝文件时间戳,需要copystat。

shutil.copystat(src, dst): 从src复制权限位,最后访问时间,最后修改时间,flag到dst。该文件的内容,所有者和组不受影响。 src和dst的是给定的字符串路径名。

from shutil import *
import os
import time def show_file_info(filename):
stat_info = os.stat(filename)
print '\tMode :', stat_info.st_mode
print '\tCreated :', time.ctime(stat_info.st_ctime)
print '\tAccessed:', time.ctime(stat_info.st_atime)
print '\tModified:', time.ctime(stat_info.st_mtime) with open('file_to_change.txt', 'wt') as f:
f.write('content')
os.chmod('file_to_change.txt', 0444) print 'BEFORE:'
show_file_info('file_to_change.txt')
copystat('shutil_copystat.py', 'file_to_change.txt')
print 'AFTER:'
show_file_info('file_to_change.txt')

shutil.rmtree(path[, ignore_errors[, onerror]]):递归的去删除文件

'''
shutil.rmtree(path[, ignore_errors[, onerror]]):递归的去删除文件
'''
import shutil
shutil.rmtree('folder1') # import os,sys
# shutil.rmtree(os.path.dirname(__file__)+"/c") # 删除 c目录 类似 rm -fr 不存在目录则报错

shutil.copytree(src, dst, symlinks=False, ignore=None):递归的去拷贝文件夹

'''
8、shutil.copytree(src, dst, symlinks=False, ignore=None):递归的去拷贝文件夹
'''
import shutil
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除
import shutil
shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))#通常的拷贝都把软连接拷贝成硬链接,即对待软连接来说,创建新的文件

shutil.move(src, dst):递归的去移动文件,它类似mv命令,其实就是重命名。

'''
10、shutil.move(src, dst):递归的去移动文件,它类似mv命令,其实就是重命名。
'''
import shutil shutil.move('folder1', 'folder3')
# shutil.move("c","b1") # 剪切c目录到b目录下 ,src即c目录不存在则报错 ,dst即b目录不存在就是重命名

压缩解压缩

shutil.make_archive(base_name, format,...)

a.创建压缩包并返回文件路径,例如:zip、tar

b.创建压缩包并返回文件路径,例如:zip、tar

    • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
      如:www                        =>保存至当前路径
      如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
    • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
    • root_dir: 要压缩的文件夹路径(默认当前目录)
    • owner: 用户,默认当前用户
    • group: 组,默认当前组
    • logger: 用于记录日志,通常是logging.Logger对象
# 将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
import shutil ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test') # 将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
import shutil ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
# import os,sys
# shutil.make_archive("my_bak","gztar",root_dir=os.path.dirname(__file__)+"/b1")
# shutil.make_archive(os.path.dirname(__file__)+"/a/my_bak","gztar",root_dir=os.path.dirname(__file__)+"/b1")

  c.shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

zipfile模块处理

import zipfile

# 压缩
# z = zipfile.ZipFile('laxi.zip', 'w')
# z.write('log.log')
# z.write('first.xml')
# z.close() # 添加一个文件
# z = zipfile.ZipFile('laxi.zip', 'a')
# z.write('first1.xml')
# z.write('a/a') # 将a目和其下面的a文件一同录压缩到里面 如果存在会保存,但是仍然压缩进入
# z.write('b/c') # 将b目录和其下面的c文件一同压缩到里面
# z.write('b/b') # 将b目录和其下面的c文件一同压缩到里面
# z.close() # 解压
# z = zipfile.ZipFile('laxi.zip', 'r')
# z.extractall("log.log") # 解药所有文件到log.log目录
# z.extract("log.log") # 解压单个文件log.log到当前目录 文件如果存在也无报错
# z.extract("first.xml") # 解压单个文件log.log到当前目录 文件如果存在也无报错
# z.close()

  tarfile模块处理

import tarfile,os
# 压缩
# tar = tarfile.open("your.tar",'w') # 已存在不报错
# tar.add(os.path.dirname(__file__),arcname="nonosd") #将前面的目录重新改名为nonosd目录名 归档到your.tar中
# tar.add("first.xml",arcname="first.xml") #将前面的目录重新改名为nonosd目录名 归档到your.tar中
# tar.close() # tar = zipfile.ZipFile('laxi.zip', 'a')
# tar.write('first1.xml')
# tar.write('a/a') # 将a目和其下面的a文件一同录压缩到里面 如果存在会保存,但是仍然压缩进入
# tar.write('b/c') # 将b目录和其下面的c文件一同压缩到里面
# tar.write('b/b') # 将b目录和其下面的c文件一同压缩到里面
# tar.close() # 压缩
# tar = tarfile.open('your.tar','r')
# # print(tar.getmembers())
# print(tar.getnames()) #查看所有的文件名
# tar.extract('first.xml') #解压单个文件
# tar.extractall(path="a/") # 解压所有到 path
# tar.close()

  

1、shutil.copyfileobj(fsrc, fdst[, length]):将文件内容拷贝到另一个文件中

1 '''
2 1、shutil.copyfileobj(fsrc, fdst[, length]):将文件内容拷贝到另一个文件中
3 '''
4 import shutil
5 shutil.copyfileobj(open('old.xml', 'r'), open('new.xml', 'w'))

2、shutil.copyfile(src, dst):拷贝文件

1 '''
2 2、shutil.copyfile(src, dst):拷贝文件
3 '''
4 import shutil
5 shutil.copyfile('f1.log', 'f2.log')

3、shutil.copymode(src, dst):仅拷贝权限。内容、组、用户均不变

1 '''
2 3、shutil.copymode(src, dst):仅拷贝权限。内容、组、用户均不变
3 '''
4 import shutil
5 shutil.copymode('f1.log', 'f2.log')

4、shutil.copystat(src, dst):拷贝状态的信息,包括:mode bits, atime, mtime, flags

1 '''
2 4、shutil.copystat(src, dst):拷贝状态的信息,包括:mode bits, atime, mtime, flags
3 '''
4 import shutil
5 shutil.copystat('f1.log', 'f2.log')

5、shutil.copy(src, dst):拷贝文件和权限

1 '''
2 5、shutil.copy(src, dst):拷贝文件和权限
3 '''
4 import shutil
5 shutil.copy('f1.log', 'f2.log')

6、shutil.copy2(src, dst):拷贝文件和状态信息

1 '''
2 6、shutil.copy2(src, dst):拷贝文件和状态信息
3 '''
4 import shutil
5 shutil.copy2('f1.log', 'f2.log')

7、shutil.ignore_patterns(*patterns)

8、shutil.copytree(src, dst, symlinks=False, ignore=None):递归的去拷贝文件夹

1 '''
2 8、shutil.copytree(src, dst, symlinks=False, ignore=None):递归的去拷贝文件夹
3 '''
4 import shutil
5 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除
1 import shutil
2 shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))#通常的拷贝都把软连接拷贝成硬链接,即对待软连接来说,创建新的文件

python模块之shutil高级文件操作的更多相关文章

  1. python3之shutil高级文件操作

    1.shutil高级文件操作模块 shutil模块提供了大量的文件的高级操作.特别针对文件拷贝和删除,主要功能为目录和文件操作以及压缩操作.对单个文件的操作也可参见os模块. 2.shutil模块的拷 ...

  2. shutil 高级文件操作

    High-level file operations  高级的文件操作模块,官网:https://docs.python.org/2/library/shutil.html# os模块提供了对目录或者 ...

  3. Python的高级文件操作(shutil模块)

    Python的高级文件操作(shutil模块) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 如果让我们用python的文件处理来进行文件拷贝,想必很多小伙伴的思路是:使用打开2个 ...

  4. (Python )格式化输出、文件操作、json

    本节学习Python的格式化输出,文件操作以及json的简单用法 1.格式化输出 将非字符串类型转换成字符串,可以使用函数:str() 或者repr() ,(这两个函数的区别目前我还没搞懂,求解答) ...

  5. 第3章 文件I/O(7)_高级文件操作:存储映射

    8. 高级文件操作:存储映射 (1)概念: 存储映射是一个磁盘文件与存储空间的一个缓存相映射,对缓存数据的读写就相应的完成了文件的读写. (2)mmap和munmap函数 头文件 #include&l ...

  6. 第3章 文件I/O(6)_高级文件操作:文件锁

    7. 高级文件操作:文件锁 (1)文件锁分类 分类依据 类型 说明 按功能分 共享读锁 文件描述符必须读打开 一个进程上了读锁,共它进程也可以上读锁进行读取 独占写锁 文件描述符必须写打开 一个进程上 ...

  7. 【Python】 高级文件操作 shutil

    shutil 很多时候,我想要对文件进行重命名,删除,创建等操作的时候的想法就是用subprocess开一个子进程来处理,但是实际上shutil可以更加方便地提供os的文件操作接口,从而可以一条语句搞 ...

  8. Python3-shutil模块-高级文件操作

    Python3中的shutil模块提供了对文件和容器文件的一些高级操作 shutil.copy(src, dst) 拷贝文件,src和dst为路径的字符串表示,copy()会复制文件数据和文件权限,但 ...

  9. python开发_xml.etree.ElementTree_XML文件操作_该模块在操作XML数据是存在安全隐患_慎用

    xml.etree.ElementTree模块实现了一个简单而有效的用户解析和创建XML数据的API. 在python3.3版本中,该模块进行了一些修改: xml.etree.cElementTree ...

随机推荐

  1. 使用 MVVMLight 消息通知

    欢迎阅读我的MVVMLight教程系列文章<关于 MVVMLight 设计模式系列> 在文章的其实我们就说了,MVVMLight的精华就是消息通知机制,设计的非常不错.这个东西在MVVML ...

  2. Entity Framework底层操作封装V2版本号(4)

    这个版本号里面.由于涉及到了多库的操作.原有的系统方法不能做到这种事情了.所以这里有了一点差别 这个类的主要用作就是,连接字符串的作用,默认是指向默认配置里面的,可是你能够指向其它的连接 using ...

  3. 超全面的JavaWeb笔记day23<AJAX>

    AJAX AJAX概述 1 什么是AJAX AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”.即使用Javascript语言 ...

  4. python中模块,包,库

    模块:就是.py文件,里面定义了一些函数和变量,需要的时候就可以导入这些模块. 包:在模块之上的概念,为了方便管理而将文件进行打包.包目录下第一个文件便是 __init__.py,然后是一些模块文件和 ...

  5. ionic调用数据接口(post、解决 payload 问题)

    $http({method:'POST', url:apiUrl, headers:{'Content-Type': 'application/x-www-form-urlencoded; chars ...

  6. MongoDB 用户角色

    Read:允许用户读取指定数据库 readWrite:允许用户读写指定数据库 dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建.删除,查看统计或访问system.profile user ...

  7. m4a文件在iOS上的流媒体播放

    Date: 2016-03-23 Title: m4a文件在iOS上的流媒体播放 Tags: m4a, mp4, iOS, Android URL: m4a-streaming-play-on-mob ...

  8. Ubuntu13.10:[3]如何开启SSH SERVER服务

    作为最新版本的UBUNTU系统而言,开源,升级全部都不在话下.传说XP已经停止补丁更新了,使用UBUNTU也是一个很好的选择.ubuntu默认安装完成后只有ssh-agent(客户端模式),宾哥百度经 ...

  9. 树形dp-hdu-3721-Building Roads

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=3721 题目意思: 给一颗树,求移动一条边(边权值不变)到另外的位置,还是一棵树.求最小的树的直径. ...

  10. MyBatis官方文档——入门

    入门 安装 要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于 classpath 中即可. 如果使用 Maven 来构建项目,则需将下面的 dependency 代码置于 ...