zoukankan      html  css  js  c++  java
  • python

    python中的shutil的作用是用来处理文件,是一种高层次的文件操作工具

    在使用shutil模块之前,我们先导入shutil模块,在看看里面的主要方法:

     1 '''shutil 高级的 文件、文件夹、压缩包 处理模块'''
     2 
     3 '''       src参数表示源文件   dst参数表示目标文件
    4 shutil.copyfileobj(fsrc,fdst[,length]) 将文件内容(打开文件,fsrc至少能读,fdst至少能写入)拷贝到另一个文件中,可以部分内容
    使用eg: shutil.copyfileobj(open('test.py','r'),open('test.bak.py','w'))

    5 shutil.copyfile(src,dst) 拷贝文件,返回目标文件名
    eg: shutil.copyfile('test.py','test_hello.py')

    6 shutil.copymode(src,dst) 仅拷贝权限。内容、组、用户均不变
    eg:shutil.copymode('test.py','test_hello.py')
    7 shutil.copystat(src,dst) 拷贝状态信息,包括mode bits,atime,mtime,flags
    eg: shutil.copystat('test.py','test_hello.py')
    8 shutil.copy(src,dst) 拷贝文件和权限
    eg: shutil.copy('test.py','test_copy.py')
    9 shutil.copy2(src,dst) 拷贝文件和状态信息
    eg: shutil.copy2('test.py','test_copy2.py')
    10 shutil.ignore_patterns(*patterns)
    11 shutil.copytree(src,dst,symlinks-Flase,ignore=None) 递归的去拷贝文件,ignore为忽略规则 eg: shutil.copytree('old_dir','new_dir') 把old_dir完整复制一份,并命名为new_dir
    更高级用法:shutil.copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*')) 忽略*.pyc、tmp*文件
    13 shutil.rmtree(path[, ignore_errors[, onerror]]) 递归的去删除文件
    eg: shutil.rmtree('test_dir') 删除当前目录下的test_dir目录及其子目录和文件
    14 shutil.move(src, dst) 递归的去移动文件,同目录相当于改名(win下目录间用\,linux下目录间用)
    eg: shutil.move('test1','test\test3') win下把目录test1移动到当前文件夹test下,并改名为test3。跟mv命令效果一样
    15 shutil.make_archive(base_name, format[,root_dir=None[,owner=None[,group=None[,logger=None]]]])
    创建压缩包并返回文件路径,例如:zip、tar
    • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
      如: test  => 保存至当前路径
      如:/Users/root/test  =>  保存至/Users/root/test/
    • format: 压缩包种类,"zip", "tar", "bztar","gztar"
    • root_dir: 要压缩的文件夹路径(默认当前目录) 可以是相对路径目录,也可以是绝对路径目录
    • owner: 用户,默认当前用户
    • group: 组,默认当前组
    • logger: 用于记录日志,通常是logging.Logger对象
           eg:   shutil.make_archive('F:\test','zip','c:\test')   把c:\下的test文件夹压缩到f:\下的test.zip
    26 '''
  • 相关阅读:
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    《EffectiveJava中文第二版》 高清PDF下载
    《MoreEffectiveC++中文版》 pdf 下载
    《啊哈c语言》 高清 PDF 下载
  • 原文地址:https://www.cnblogs.com/xtsec/p/6679967.html
Copyright © 2011-2022 走看看