shutil 拷贝 / 移动 / 压缩 / 解压缩

时间:2022-09-03 16:39:47
# shutil_demo.py 高级文件操作(拷贝 / 移动 / 压缩 / 解压缩)  

import shutil  

def shutil_demo():
# 拷贝文件
shutil.copy2('file.txt', 'temp.txt') # 拷贝目录
shutil.copytree("root", "temp", symlinks=False, ignore=shutil.ignore_patterns("*.pyc"), copy_function=shutil.copy2, ignore_dangling_symlinks=True) # 删除目录
shutil.rmtree("temp", ignore_errors=True) # 移动文件/目录
shutil.move("root", "temp", copy_function=shutil.copy2) # 获取磁盘使用空间
total, used, free = shutil.disk_usage(".")
print("当前磁盘共: %iGB, 已使用: %iGB, 剩余: %iGB"%(total / 1073741824, used / 1073741824, free / 1073741824)) # 压缩文件
shutil.make_archive('Box', 'zip', 'temp') # 解压文件
shutil.unpack_archive('Box.zip') def shutil_func():
# 文件和目录操作
# shutil.copyfileobj(fsrc, fdst[, length]) // 拷贝文件内容, 将fsrc文件里的内容copy到fdst文件中, length:缓冲区大小
shutil.copyfileobj(open('file.txt', 'r'), open('temp.txt', 'w'))
# shutil.copyfile(src, dst, *, follow_symlinks=True) // 拷贝文件内容, 同copyfileobj, 如果dst=src,抛SameFileError异常, dst存在则替换
dst = shutil.copyfile('file.txt', 'temp.txt')
# shutil.copymode(src, dst, *, follow_symlinks=True) // 仅拷贝权限, 其他信息不受影响
shutil.copymode('file.txt', 'temp.txt')
# shutil.copystat(src, dst, *, follow_symlinks=True) // 拷贝状态(权限 / 最后访问时间 / 上次修改时间 / 标志), 其他不受迎影响
shutil.copystat('file.txt', 'temp.txt')
# shutil.copy(src, dst, *, follow_symlinks=True) // 拷贝文件(数据 / 权限)
dst = shutil.copy('file.txt', 'temp.txt')
# shutil.copy2(src, dst, *, follow_symlinks=True) // 拷贝文件(尝试保留所有元数据) (不能拷贝创建时间,该时间可通过修改系统时间再创建文件来实现)
dst = shutil.copy2('file.txt', 'temp.txt')
# shutil.ignore_patterns(*patterns)
# symlinks:True(复制链接) / False(复制文件), ignore=ignore_patterns("") // 忽略的文件, copy_function=自定义复制函数, ignore_dangling_symlinks:True(忽略文件不存在异常) / False(错误列表中添加异常)
# shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False) // 递归的复制根目录下的整个目录树
dst = shutil.copytree("root", "temp", symlinks=False, ignore=shutil.ignore_patterns("*.pyc"), copy_function=shutil.copy2, ignore_dangling_symlinks=True)
# shutil.rmtree(path, ignore_errors=False, onerror=None) // 删除整个目录树, ignore_errors:是否忽略删除失败错误, onerror=def error(func, path, excinfo)
shutil.rmtree("temp", ignore_errors=True)
# shutil.move(src, dst, copy_function=copy2) // 递归移动文件/目录, 目录存在则移动目录, 文件存在则覆盖
dst = shutil.move("root", "temp", copy_function=shutil.copy2)
total, used, free = shutil.disk_usage(".") # 给定路径的磁盘使用情况统计信息
# shutil.chown(path, user=None, group=None) // 修改用户和组 (Unix可用)
# shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None) // 可执行文件路径, path:要查找的路径,未指定使用os.environ的结果
path_str = shutil.which("python") # 异常
try: pass
except shutil.SameFileError: pass # copyfile()时,源和目录是同一个文件时,抛此异常
except shutil.Error: pass # copytree()时, 多文件操作时引发的异常, 异常包含(srcname, dstname, excinfo) # 压缩文件操作 (封装了zipfile / tarfile)
# 创建归档文件 base_name:压缩包文件名, format:格式 zip / tar / bztar / xztar / gztar, root_dir:被归档的根目录(默认当前目录)
# base_dir:保存归档文件的目录(默认当前目录) verbose:已弃用 dry_run:True(不创建归档,但记录日志), owner:用户, group:用户组, logger:日志
# shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])
dst = shutil.make_archive('Box', 'zip', 'temp') # 注意:root_dir / base_dir至少写一个,不然会造成压缩包再次被打包的情况
# 分拆归档, filename:文件名, extract_dir:解压到目录(默认当前目录), format:格式 (未提供,根据扩展名查找,未找到引发ValueError)
# shutil.unpack_archive(filename[, extract_dir[, format]])
shutil.unpack_archive('Box.zip') lists = shutil.get_archive_formats() # 返回支持的归档格式列表[(format, info)]
lists = shutil.get_unpack_formats() # 返回所有注册格式的列表[(name, extensions, description)] # 注册压缩格式, name:格式名, function:def func(base_name, base_dir, owner, group, dry_run, logger), extra_args:额外参数, description:说明信息
# shutil.register_archive_format(name, function[, extra_args[, description]])
# shutil.unregister_archive_format(name) // 注销压缩格式
# 注册解压格式 name:格式名, extensions:扩展名列表, function:实现函数 def unpack(filename, extract_dir), extra_args:额外参数(name, value), description:说明
# shutil.register_unpack_format(name, extensions, function[, extra_args[, description]])
# shutil.unregister_unpack_format(name) // 注销解压格式 # 终端
# shutil.get_terminal_size(fallback=(columns, lines))
columns, lines = shutil.get_terminal_size() # 查询终端大小(宽, 高), 无法查询返回默认大小(80, 24) if __name__ == "__main__":
shutil_demo() # shutil_func()

  

shutil 拷贝 / 移动 / 压缩 / 解压缩的更多相关文章

  1. linux 配置网卡、远程拷贝文件、建立软硬链接、打包/解包、压缩/解压缩、包操作、yum配置使用、root密码忘记

    目录 一.配置网卡 二.xshell连接 三.远程拷贝文件 四.建立软硬连接 五.打包/解包和压缩/解压缩 六.包操作 七.配置yum源 配置yum源 配置阿里云源 常用命令 yum其他命令 八.重置 ...

  2. hadoop的压缩解压缩,reduce端join,map端join

    hadoop的压缩解压缩 hadoop对于常见的几种压缩算法对于我们的mapreduce都是内置支持,不需要我们关心.经过map之后,数据会产生输出经过shuffle,这个时候的shuffle过程特别 ...

  3. Linux下的压缩解压缩命令详解

    linux zip命令zip -r myfile.zip ./*将当前目录下的所有文件和文件夹全部压缩成myfile.zip文件,-r表示递归压缩子目录下所有文件. 2.unzipunzip -o - ...

  4. Qt之QuaZIP(zip压缩/解压缩)

    简述 QuaZIP是使用Qt/C++对ZLIB进行简单封装的用于压缩及解压缩ZIP的开源库.适用于多种平台,利用它可以很方便的将单个或多个文件打包为zip文件,且打包后的zip文件可以通过其它工具打开 ...

  5. Linux/centos/redhat下各种压缩解压缩方式详解

    1.zip命令 zip -r myfile.zip ./* 将当前目录下的所有文件和文件夹全部压缩成myfile.zip文件,-r表示递归压缩子目录下所有文件. 2.unzip unzip -o -d ...

  6. ICSharpCode.SharpZipLib实现压缩解压缩

    最近,在项目中经常需要处理压缩和解压缩文件的操作.经过查找,发现了ICSharpCode.SharpZipLib.dll ,这是一个完全由c#编写的Zip, GZip.Tar . BZip2 类库,可 ...

  7. 使用 apache ant 轻松实现文件压缩/解压缩(转)

    原文地址:http://blog.csdn.net/irvine007/article/details/6779492 maven配置ant包: <dependency> <grou ...

  8. 使用VC&plus;&plus;压缩解压缩文件夹

    前言   项目中要用到一个压缩解压缩的模块, 看了很多文章和源代码,  都不是很称心, 现在把我自己实现的代码和大家分享. 要求: 1.使用Unicode(支持中文). 2.使用源代码.(不使用静态或 ...

  9. 基于ICSharpCode&period;SharpZipLib&period;Zip的压缩解压缩

    原文:基于ICSharpCode.SharpZipLib.Zip的压缩解压缩 今天记压缩解压缩的使用,是基于开源项目ICSharpCode.SharpZipLib.Zip的使用. 一.压缩: /// ...

随机推荐

  1. iOS 全局断点崩溃

    设置全局断点出现奔溃,可以点击继续运行不影响程序,不是程序的问题,webview和自定义xib View使用的时候

  2. &lbrack;C&num;&rsqb;集合已修改;可能无法执行枚举操作

    摘要 我相信很多人对这个再熟悉不过了.对已经修改的集合进行操作就会出现这个错. 解决办法 比如有下面的一段代码,我们创建一个集合,并向集合中添加10个数,然后,我们循环再将这些数移除了. static ...

  3. Sprint&lpar;第四天11&period;17&rpar;

    燃尽图

  4. python ljust&comma;rjust&comma;center&comma;zfill对齐使用方法

    字符串在输出时的对齐:S.ljust(width,[fillchar]) #输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格. S.rjust(width,[fillcha ...

  5. Arch tty终端使用中文,Fbterm控制台配置

    参考: http://www.linuxidc.com/Linux/2011-08/40746p2.htm 安装: # pacman -S fbterm fcitx-fbterm # sudo gpa ...

  6. Troubleshooting &amp&semi;quot&semi;Global Enqueue Services Deadlock detected&amp&semi;quot&semi; &lpar;Doc ID 1443482&period;1&rpar;

    In this Document   _afrLoop=1021148011984950&id=1443482.1&displayIndex=1&_afrWindowMode= ...

  7. HTML-中&lt&semi;li&gt&semi;标签value值的兼容问题

    今天在做项目测试的时候,发现IE浏览器对HTML中<li>标记的value取值存在兼容性问题,特意从4个浏览器出发进行了一些测试.现将测试结论展示如下: 测试类型 IE8 FF16.0.1 ...

  8. maven构建失败。

    maven项目编译报“Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1” 解决方案:setting.x ...

  9. SAP MM &&num;39&semi;独立&sol;集中&&num;39&semi;等于1的MTS物料MRP运行后合并需求触发PR

    SAP MM '独立/集中'等于1的MTS物料MRP运行后合并需求触发PR Test data 独立与集中: 1 (仅个别需求) STO 1, 这是一个公司间STO,从国内生产基本转入香港贸易公司, ...

  10. rinetd 通过公网连接云数据库

    在很多云服务中,经常会遇到云存储数据库没有公网(外网)地址,只有内网地址,这导致在公司网无法访问,这是一个很困扰的问题,这时我们可以使用rinetd进行转发实现外网连接. 首先需要一台能够连接上数据库 ...