详解Python_shutil模块

yipeiwu_com5年前Python基础

import shutil

高级的文件,文件夹,压缩包的处理模块,也主要用于文件的拷贝

shutil.copyfileobj(fsrc,fdst[,length]):  将文件的内容拷贝到另一个文件(可以指定length长度进行拷贝)

import shutil
shutil.copyfileobj(open('old.txt','r'),open('new.txt','w'))

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

import shutil
shutil.copyfile('f1.log','f2.log')

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

import shutil
shutil.copymode('f1.log', 'f2.log')

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

import shutil
shutil.copystat('f1.log', 'f2.log')

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

import shutil
shutil.copy('f1.log', 'f2.log')

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

import shutil
shutil.copy2('f1.log', 'f2.log')

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

import shutil
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))

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

import shutil
shutil.rmtree('folder1')

shutil.move(src,dst):  递归的去移动文件(重命名)

import shutil
shutil.move('folder1', 'folder3')

shutil.make_archive(base_name, format,...):  创建压缩包并返回文件路径,例如:zip、tar

base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径(例:Presley=>保存至当前路径,/User/Presley =>保存至/Users/路径下)
format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
root_dir: 要压缩的文件夹路径(默认当前目录)
owner: 用户,默认当前用户
group: 组,默认当前组

import shutil
z = shutil.make_archive('presly', 'gztar', root_dir='D:\软件下载')

shutil对压缩包的处理,也可调用zipfile或tarfile模块进行压缩

以上所述是小编给大家介绍的Python_shutil模块详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

pyinstaller 3.6版本通过pip安装失败的解决办法(推荐)

pyinstaller 3.6版本通过pip安装失败的解决办法(推荐)

本机中原pyinstaller版本为3.5版本,本打算通过 pip install --upgrade pyinstaller进行升级,竟然报错,后面卸载再重新安装也一样报错,没办法看来...

Python中字符串格式化str.format的详细介绍

前言 Python 在 2.6 版本中新加了一个字符串格式化方法: str.format() 。它的基本语法是通过 {} 和 : 来代替以前的 %.。 格式化时的占位符语法: rep...

Python3 解决读取中文文件txt编码的问题

Python3 解决读取中文文件txt编码的问题

问题描述 尝试用Python写一个Wordcloud的时候,出现了编码问题。 照着网上某些博客的说法添添改改后,结果是变成了“UnicodeDecodeError: ‘utf-8' c...

Python删除windows垃圾文件的方法

本文实例讲述了Python删除windows垃圾文件的方法。分享给大家供大家参考。具体如下: #coding:utf-8 import os #from glob import gl...

Python调用百度根据经纬度查询地址的示例代码

如下所示: def locatebyLatLng(lat, lng, pois=0): ''' 根据经纬度查询地址 ''' items = {'location': str(...