python学习之路(常用系统模块4--shutil模块)
2017-12-23 18:50
585 查看
shutil
以下方法需要import shutilshutil.copyfileobj(fsrc, fdst, length=16384)
将文件内容拷贝到另一个文件中,可以部分内容
例:
import shutil with open('a.txt','r',encoding='utf-8') as f1, open('copy_a','w',encoding='utf-8') as f2: shutil.copyfileobj(f1,f2)
shutil.copyfile(src, dst, *, follow_symlinks=True)
copy文件 与copyfileobj区别是,这个方法不需要open,可以直接将文件名传给参数
例:
shutil.copyfile('a.txt','copy_a') # 实现上面例子同样的效果。
shutil.copymode(src, dst, *, follow_symlinks=True)
将权限copy给其他的文件或目录
shutil.copystat(src, dst, *, follow_symlinks=True)
将本文件属性复制给其他的目录或文件
shutil.copy(src, dst, *, follow_symlinks=True)
将文件和权限都copy给其他的文件和目录
shutil.copy2(src, dst)
将文件和状态属性都copy给其他的文件和目录
shutil.copytree(‘原文件目录’,’新文件目录’)
将文件目录,递归copy将里面所有的目录与文件都进行copy一份。
shutil.rmtree(‘文件目录’)
递归进行删除。
shutil.move(‘旧文件’,’新文件’)
递归去移动文件
shutil.make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,dry_run=0, owner=None, group=None, logger=None)
创建压缩包并返回文件路径,例如:zip、tar
base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
如:www =>保存至当前路径
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
root_dir: 要压缩的文件夹路径(默认当前目录)
owner: 用户,默认当前用户
group: 组,默认当前组
logger: 用于记录日志,通常是logging.Logger对象
zipfile&tarfile
其实shutil的压缩,就是调用ZipFile 和 TarFile 模块这里说以下这两个模块
zipfile压缩
import zipfile ZIPFILE_ZIP_FILE = zipfile.ZipFile('test.zip', 'w') # w 代表写入到这个压缩文件 ZIPFILE_ZIP_FILE.write('a.txt') # 写入 a.txt ZIPFILE_ZIP_FILE.write('copy_a1') # 再写入 copy_a1 ZIPFILE_ZIP_FILE.close() # 记得关闭文件
生成如上的压缩文件
zipfile解压
file = zipfile.ZipFile('test.zip', 'r') # r是读zip文件 file.extractall() # 解压所有 file.close() # 关闭文件
tarfile压缩
与zipfile 一样的方式,import tarfile tarfile_open= tarfile.open('test.tar', 'w') tarfile_open.add('a.txt') tarfile_open.add('copy_a1') tarfile_open.close()
tarfile解压
tarfile_open = tarfile.open('test.tar', 'r') tarfile_open.extractall() # 可设置解压地址 tarfile_open.close()
相关文章推荐
- python学习之路(常用系统模块1--时间模块)
- Python3内置模块详解1 (Python 之路 Day5 - 常用模块学习 )
- Python 之路 Day5 - 常用模块学习
- python学习之路-7 模块configparser/xml/shutil/subprocess以及面向对象初级入门
- python之路-16-常用模块学习
- Python 之路 Day5 - 常用模块学习
- Python 之路 Day5 - 常用模块学习
- 我的python学习之路---命行选项模块optparse
- python 学习笔记 14 -- 常用的时间模块之datetime
- python模块学习——shutil
- 【学习ios之路:Objective-C】OC中常用的系统排序方法
- python 学习笔记 os模块常用项
- Python shutil模块学习
- python学习――模块和模块的常用方法
- python学习笔记 常用第三方模块
- python入门学习(1)——脚本(常用系统相关命令)
- 我的python学习之路--如何写python模块
- python shutil模块学习
- python shutil模块学习
- 学习Python必须要知道的常用模块