高级的 文件、文件夹、压缩包 处理模块
shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中:
#源码 def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf)
#复制文件 import shutil f = open(‘settings.py‘, ‘rb‘) f1 = open(‘aaa.py‘, ‘wb‘) shutil.copyfileobj(f, f1, length=20) f.close() f1.close()
shutil.copyfile(src, dst)
拷贝文件
#源码i def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) for fn in [src, dst]: try: st = os.stat(fn) except OSError: # File most likely does not exist pass else: # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): raise SpecialFileError("`%s` is a named pipe" % fn) with open(src, ‘rb‘) as fsrc: with open(dst, ‘wb‘) as fdst: copyfileobj(fsrc, fdst)
shutil.copymode(src, dst)
只拷贝权限,内容、组、用户均不变
#源码 def copymode(src, dst): """Copy mode bits from src to dst""" if hasattr(os, ‘chmod‘): st = os.stat(src) mode = stat.S_IMODE(st.st_mode) os.chmod(dst, mode)
示例:
#第一步,查看文件权限 # ll 总用量 16 drwxrwxr-x 2 huangxm huangxm 4096 3月 24 14:32 ./ drwxrwxr-x 6 huangxm huangxm 4096 3月 24 14:32 ../ -rw-rw-r-- 1 huangxm huangxm 49 3月 24 14:32 aaa.txt -rw-r--r-- 1 root root 29 3月 24 14:32 bbb.txt #第二步,新建ccc.py,写入以下代码: #!/usr/bin/env python3 import shutil #将bbb.txt的文件权限复制给aaa.txt shutil.copymode(‘bbb.txt‘, ‘aaa.txt‘) #python3 ccc.py执行代码 #第三步:查看文件权限 # ls -l 总用量 12 -rw-r--r-- 1 huangxm huangxm 49 3月 24 14:32 aaa.txt -rw-r--r-- 1 root root 29 3月 24 14:32 bbb.txt -rw-r--r-- 1 root root 77 3月 24 14:35 ccc.py
shutil.copystat(src, dst)
拷贝状态信息,包括:mode bits, atime, mtime, flags
#源码 def copystat(src, dst): """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, ‘utime‘): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, ‘chmod‘): os.chmod(dst, mode) if hasattr(os, ‘chflags‘) and hasattr(st, ‘st_flags‘): try: os.chflags(dst, st.st_flags) except OSError, why: for err in ‘EOPNOTSUPP‘, ‘ENOTSUP‘: if hasattr(errno, err) and why.errno == getattr(errno, err): break else: raise
shutil.copy(src, dst)
拷贝文件和权限
#源码 def copy(src, dst): """Copy data and mode bits ("cp src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copymode(src, dst)
shutil.copy2(src, dst)
拷贝文件和状态信息
#源码 def copy2(src, dst): """Copy data and all stat info ("cp -p src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copystat(src, dst)
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
src = ‘D:/temp/python/zuoye/day6‘ #当前目录的zy_d6文件夹,不需要提前创建 dst = ‘zy_d6‘ #要排除的文件,可以多个用,分隔 支持通配符比如temp* ignore_file = shutil.ignore_patterns(‘*.py‘) shutil.copytree(src, dst, ignore=ignore_file)
shutil.rmtree(path)
递归删除文件
shutil.move(src, dst)
递归移动文件
shutil.make_archive(base_name, format, …)
创建压缩包并返回文件路径,例如: zip、tar
base_name: 压缩包的文件名,也可以是压缩包的路径。文件名是保存到当前路径,路径时保存到指定路径
format: 压缩包种类, zip, tar, bztar, gztar
root_dir: 要压缩的文件夹路径(默认当前目录)
owner: 用户, 默认当前用户
group: 组,默认当前组
logger: 用户于记录日志,通常是logging.Logger对象
#将当前目录打包放到当前目录下 ret = shutil.make_archive(‘dq‘, ‘gztar‘)
返回值是压缩包名称,上例中ret的值是 dq.tar.gz
#将指定目录打包放到当前目录 root_dir = ‘D:/temp/python/zuoye/day6‘ ret = shutil.make_archive(‘dq‘, ‘gztar‘, root_dir=rootdir) print(ret)
shutil 对压缩包的处理是调用ZipFile和TarFile两个模块来进行的,详细:
import zipfile # 压缩 z = zipfile.ZipFile(‘laxi.zip‘, ‘w‘) z.write(‘a.log‘) z.write(‘data.data‘) z.close() # 解压 z = zipfile.ZipFile(‘laxi.zip‘, ‘r‘) z.extractall() z.close()
import tarfile # 压缩 tar = tarfile.open(‘your.tar‘,‘w‘) tar.add(‘/Users/wupeiqi/PycharmProjects/bbs2.zip‘, arcname=‘bbs2.zip‘) tar.add(‘/Users/wupeiqi/PycharmProjects/cmdb.zip‘, arcname=‘cmdb.zip‘) tar.close() # 解压 tar = tarfile.open(‘your.tar‘,‘r‘) tar.extractall() # 可设置解压地址 tar.close()
时间: 2024-10-19 14:29:05