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

Python3中的shutil模块提供了对文件和容器文件的一些高级操作

  shutil.copy(src, dst)

    拷贝文件,src和dst为路径的字符串表示,copy()会复制文件数据和文件权限,但是其他的元数据(如:修改时间)不会保留,如果要保留请用copy2()

  shutil.copyfileobj(fsrc, fdst[, length])

    拷贝文件对象,fsrc和fdst为两个打开的文件对象

  shutil.copyfile(src, dst)

    拷贝文件,src和dst为路径的字符串表示

  shutil.copymode(src, dst)

    仅拷贝文件的权限

  shutil.copystat(src, dst)

    将权限位,最后访问时间,上次修改时间和标志从src复制到dst

  shutil.copytree(src, dst)

    拷贝整个目录树,dst不能存在

  shutil.rmtree(path)

    删除整个目录树

  shutil.move(src, dst)

    移动文件或目录

  shutil.disk_usage(path)

    返回指定路径的磁盘使用情况统计信息,单位为字节

import shutil

du = shutil.disk_usage("E:\\")
print("总大小:%s G" % (round(du.total / 1024 / 1024 / 1024, 2)))
print("已使用:%s G" % (round(du.used / 1024 / 1024 / 1024, 2)))
print("剩余:%s G" % (round(du.free / 1024 / 1024 / 1024, 2)))
print("总大小:%s M" % (round(du.total / 1024 / 1024, 2)))
print("已使用:%s M" % (round(du.used / 1024 / 1024, 2)))
print("剩余:%s M" % (round(du.free / 1024 / 1024, 2)))
View Code

  shutil.make_archive(base_name, format, [root_dir])

    创建归档文件并返回其名称

    base_name: 要创建的文件的名称

    format: 归档的格式,支持zip tar batar gztar

    root_dir: 为要归档的目录,默认为当前目录

import shutil

zip_file = shutil.make_archive("E:\\Jet", "zip", root_dir="E:\\Jet Bi")
print(zip_file)    # 输出结果: E:\Jet.zip
View Code

  shutil.unpack_archive(filename[, extract_dir[, format]])

    分拆解压归档文件
    filename: 归档文件的完整路径

    extract_dir: 解压目标目录,默认为当前目录

    format: 解压格式,默认使用文件的扩展名

import shutil

# 将E:\Jet.zip中的内容解压到F:\Jet目录中
shutil.unpack_archive("E:\\Jet.zip", "F:\\Jet")
View Code

  shutil.get_archive_formats()

    返回支持的归档格式

  shutil.get_unpack_formats()

    返回支持分拆的归档格式

 

    

 

  

posted on 2017-03-24 17:56  AustralGeek  阅读(206)  评论(0编辑  收藏  举报

导航