shutil模块-高级的文件、文件夹、压缩包处理模块

  • shutil.copyfileobj(fsrc, fdst[, length])将文件内容拷贝到另一个文件中,length是每次复制的大小
  • guessage.py中内容
    """
    猜年龄游戏:
    允许用户最多猜三次,猜了三次后,询问是都继续玩,如果输入Y,可以继续猜三次,否则退出
    """
    age = 23
    count = 0
    while count < 3:
        try:
            guess_age = int(input("input the age of you think:"))
        except ValueError:
            print("you should input one number!")
            count = count + 1
            continue
    
        if guess_age > 23:
            print("the age you input is too big!")
        elif guess_age < 23:
            print("the age you input is too small!")
        else:
            print("excellent!you are right!")
            break
        count = count + 1
        while count == 3:
            your_choice = input("you only have three chances,would you like to continue(Y|y/N|n):")
            if your_choice.lower() == "y":
                count = 0
            elif your_choice.lower() =="n":
                break
            else:
                print("your input is illegal!input again!")
    "正确的程序运行代码"
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    shutil.copyfileobj(open("guessage.py","r",encoding="utf-8"),open("guessage_new.py","w",encoding="utf-8",10))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    
    Process finished with exit code 0
    "不加编码时,有报错信息"
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    shutil.copyfileobj(open("guessage.py","r"),open("guessage_new.py","w"))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    Traceback (most recent call last):
      File "E:/PythonProject/python-test/BasicGrammer/test.py", line 5, in <module>
        shutil.copyfileobj(open("guessage.py","r"),open("guessage_new.py","w"))
      File "D:\software2\Python3\install\lib\shutil.py", line 79, in copyfileobj
        buf = fsrc.read(length)
    UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xae in position 29: illegal multibyte sequence
    
    Process finished with exit code 1
    
    
    guessage_new.py
    """
    猜年龄游戏:
    允许用户最多猜三次,猜了三次后,询问是都继续玩,如果输入Y,可以继续猜三次,否则退出
    """
    age = 23
    count = 0
    while count < 3:
        try:
            guess_age = int(input("input the age of you think:"))
        except ValueError:
            print("you should input one number!")
            count = count + 1
            continue
    
        if guess_age > 23:
            print("the age you input is too big!")
        elif guess_age < 23:
            print("the age you input is too small!")
        else:
            print("excellent!you are right!")
            break
        count = count + 1
        while count == 3:
            your_choice = input("you only have three chances,would you like to continue(Y|y/N|n):")
            if your_choice.lower() == "y":
                count = 0
            elif your_choice.lower() =="n":
                break
            else:
                print("your input is illegal!input again!")
    
    • shutil.copyfile(src, dst)拷贝文件
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    shutil.copyfile("guessage.py","guessage_new.py")#目标文件无需存在
    print("guessage.py",os.stat("guessage.py"))
    print("guessage_new.py",os.stat("guessage_new.py"))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    guessage.py os.stat_result(st_mode=33206, st_ino=9007199254741804, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1555571381)
    guessage_new.py os.stat_result(st_mode=33206, st_ino=7881299347900196, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1557104769, st_mtime=1557104769, st_ctime=1557104769)
    
    Process finished with exit code 0
    
    • shutil.copymode(src, dst)仅拷贝权限。内容、组、用户均不变
    "程序代码"
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    shutil.copymode("guessage.py","guessage_new.py")#目标文件必须存在
    #目标文件不存在时
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    Traceback (most recent call last):
      File "E:/PythonProject/python-test/BasicGrammer/test.py", line 5, in <module>
        shutil.copymode("guessage.py","guessage_new.py")
      File "D:\software2\Python3\install\lib\shutil.py", line 144, in copymode
        chmod_func(dst, stat.S_IMODE(st.st_mode))
    FileNotFoundError: [WinError 2] 系统找不到指定的文件。: ‘guessage_new.py‘
    
    Process finished with exit code 1
    #新建一个文件guessage_new.py,内容为空,再运行程序
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    import os
    shutil.copymode("guessage.py","guessage_new.py")
    print("guessage.py",os.stat("guessage.py"))
    print("guessage_new.py",os.stat("guessage_new.py"))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    guessage.py os.stat_result(st_mode=33206, st_ino=9007199254741804, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1555571381)
    guessage_new.py os.stat_result(st_mode=33206, st_ino=2533274790397796, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=61, st_atime=1557104202, st_mtime=1557104202, st_ctime=1557104202)
    
    Process finished with exit code 0
    
    • shutil.copystat(src, dst)仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    import os
    shutil.copystat("guessage.py","guessage_new.py") #目标文件必须存在
    print("guessage.py",os.stat("guessage.py"))
    print("guessage_new.py",os.stat("guessage_new.py"))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    guessage.py os.stat_result(st_mode=33206, st_ino=9007199254741804, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1555571381)
    guessage_new.py os.stat_result(st_mode=33206, st_ino=2814749767108452, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=61, st_atime=1555571381, st_mtime=1555571381, st_ctime=1557104576)
    
    Process finished with exit code 0
    
    • shutil.copy(src, dst)拷贝文件和权限
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    import os
    shutil.copy("guessage.py","guessage_new.py")#目标文件可以不存在
    print("guessage.py",os.stat("guessage.py"))
    print("guessage_new.py",os.stat("guessage_new.py"))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    guessage.py os.stat_result(st_mode=33206, st_ino=9007199254741804, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1555571381)
    guessage_new.py os.stat_result(st_mode=33206, st_ino=6473924464346978, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1557104716, st_mtime=1557104716, st_ctime=1557104716)
    
    Process finished with exit code 0
    
    • shutil.copy2(src, dst)拷贝文件和状态信息
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    import os
    shutil.copy2("guessage.py","guessage_new.py")
    print("guessage.py",os.stat("guessage.py"))
    print("guessage_new.py",os.stat("guessage_new.py"))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    guessage.py os.stat_result(st_mode=33206, st_ino=9007199254741804, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1555571381)
    guessage_new.py os.stat_result(st_mode=33206, st_ino=7318349394478946, st_dev=3466358229, st_nlink=1, st_uid=0, st_gid=0, st_size=941, st_atime=1555571381, st_mtime=1555571381, st_ctime=1557104918)
    
    Process finished with exit code 0
    
    • shutil.ignore_patterns(*patterns)
    • shutil.copytree(src, dst, symlinks=False, ignore=None)递归的去拷贝文件夹
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    import os
    
    # 目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除
    shutil.copytree(‘ee‘, ‘new_ee‘, ignore=shutil.ignore_patterns(‘*.pyc‘, ‘tmp*‘))
    print(os.listdir("ee"))
    print(os.listdir("new_ee"))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    [‘eee‘]
    [‘eee‘]
    
    Process finished with exit code 0
    
    • shutil.rmtree(path[, ignore_errors[, onerror]])递归的去删除文件
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    import os
    
    shutil.rmtree(‘new_ee‘)
    print(os.listdir("ee"))
    print(os.listdir("new_ee"))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    Traceback (most recent call last):
    [‘eee‘]
      File "E:/PythonProject/python-test/BasicGrammer/test.py", line 10, in <module>
        print(os.listdir("new_ee"))
    FileNotFoundError: [WinError 3] 系统找不到指定的路径。: ‘new_ee‘
    
    Process finished with exit code 1
    
    • shutil.move(src, dst)递归的去移动文件,它类似mv命令,其实就是重命名。
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    import os
    
    shutil.move(‘ee‘,‘new_ee‘)
    print(os.listdir("ee"))#move之后,源文件就不存在了
    print(os.listdir("new_ee"))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    Traceback (most recent call last):
      File "E:/PythonProject/python-test/BasicGrammer/test.py", line 9, in <module>
        print(os.listdir("ee"))
    FileNotFoundError: [WinError 3] 系统找不到指定的路径。: ‘ee‘
    
    Process finished with exit code 1
    
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    import os
    shutil.move(‘new_ee‘,‘mkdir‘) #可以移到另一个文件夹中
    print(os.listdir("mkdir"))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    [‘new_ee‘]
    
    Process finished with exit code 0
    
    • shutil.make_archive(base_name, format,...)创建压缩包并返回文件路径,例如:zip、tar
    base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
    如 data_bak =>保存至当前路径
    如:/tmp/data_bak =>保存至/tmp/
    
    format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
    root_dir: 要压缩的文件夹路径(默认当前目录)
    owner: 用户,默认当前用户
    group: 组,默认当前组
    logger: 用于记录日志,通常是logging.Logger对象
    
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # Author: vita
    import shutil
    #将 test2 下的文件打包放置当前程序目录
    import shutil
    import os
    ret = shutil.make_archive("test2_bak", ‘gztar‘, root_dir=‘test2‘)#目标的压缩包可以是已经存在的
    print(os.listdir())
    #将 test2下的文件打包放置 mkdir目录
    import shutil
    ret = shutil.make_archive("mkdir/test2_bak", ‘gztar‘, root_dir=‘test2‘)
    print(os.listdir("mkdir"))
    
    E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
    [‘.idea‘, ‘guessage.py‘, ‘guessage_new.py‘, ‘mkdir‘, ‘requirements.txt‘, ‘test.py‘, ‘test2‘, ‘test2_bak.tar.gz‘, ‘__pycache__‘, ‘写文件.txt‘, ‘写文件.txt.tmp‘, ‘格式化.py‘, ‘猜年龄的游戏.jpg‘, ‘读文件.txt‘]
    [‘new_ee‘, ‘test2_bak.tar.gz‘]
    
    Process finished with exit code 0
    
    shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:
    zipfile压缩&解压缩
    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(path=‘.‘)
    z.close()
    
    tarfile压缩&解压缩
    import tarfile
    
    # 压缩,egon.tar这个压缩包可以是不存在的,并且可对文件夹递归放到压缩包中
    >>> t=tarfile.open(‘/tmp/egon.tar‘,‘w‘)
    >>> t.add(‘/test1/a.py‘,arcname=‘a.bak‘)
    >>> t.add(‘/test1/b.py‘,arcname=‘b.bak‘)
    >>> t.close()
    
    # 解压
    >>> t=tarfile.open(‘/tmp/egon.tar‘,‘r‘)
    >>> t.extractall(‘/egon‘)
    >>> t.close()

    原文地址:https://blog.51cto.com/10983441/2389582

    时间: 2024-10-21 12:02:53

    shutil模块-高级的文件、文件夹、压缩包处理模块的相关文章

    python基础学习shutil高级的文件,目录,压缩包处理模块

    shutil高级的文件,目录,压缩包处理模块import shutil 复制shutil.copyfileobj(f1,f2) #从一个文件对接复制到另一个文件对象,需要先打开文件shutil.copyfile() #拷贝文件shutil.copystat() #只拷贝文件状态信息 包括 modebits,atime,mtime,flagsshutil.copymode() #值拷贝权限.内容和组,用户均不改变shutil.copy() #拷贝文件和权限shutil.copy2() #同时拷贝文

    python动态import某个文件夹下的模块

    因为有  "用户上传脚本,动态运行"的需求,所以要动态地import用户上传的模块 所以写了个函数动态地import # -*- coding: utf-8 -*- import os import sys import os.path import Queue import commands def test(rootDir): #判断传入的路径下是否有"__init__.py"这个文件了,如果没有则创建,否则import会认为没有这个moudle if os.p

    python--导入其他文件夹下的模块(.py文件)

    适用情况:在test.py模块中需要导入其他文件下的模块model.py 方法: 在test.py模块中添加以下脚本: import syssys.path.append("model.py的文件路径")import model 导入模块关键是能够根据sys.path环境变量的值,找到具体模块的路径.

    webpack模块加载css文件及图片地址

    webpack支持css文件加载并打包,只需安装相应加载器并在配置文件中配置 . 加载的css文件内容会与该模块里的js内容混合封装,这样做的好处是一个js文件包含了所有的css与js内容,有效减少了http请求次数,显著提高了页面响应性能的用户体验. 加载css文件时,如果css里含有图片的引用地址,编译时webpack会将图片资源处理并输出到设置的publicPath参数位置,该参数可以是以页面为基准的相对地址,也可以是以根目录为基准的绝对地址.url-laoder会在这个地址下兴建一个im

    一个高级的makefile文件

    该Makefile适用于最后生成若干个可执行文件的小型C/C++工程,只要将该Makefile放在源码根目录下make,它会自动查找该目录下(包括子目录)的所有源码文件(支持.cpp .c .h格式)并自动生成正确的依赖关系,并且为了不污染源码文件夹,源码和编译过程中的中间文件会分开(Debug模式编译生成的中间文件在Debug目录下,Release模式在Release目录下). 1 ########################################################

    命令行修改文件文件夹访问权限 cacls, 修改hosts内容方法

    背景 日常使用Windows的过程中,hosts(C:\Windows\System32\drivers\etc)文件可能被一些程序串改,因此在网上找到禁止/允许修改hosts文件的bat脚本,但是在使用过程中有遇到了新的麻烦,特记录下相关问题的解决方法. 禁止/允许修改hosts文件的bat脚本 Hosts是一个没有扩展名的系统文件,可以用记事本等工具打开,其作用就是将一些常用的网址域名与其对应的IP地址建立一个关联"数据库",当用户在浏览器中输入一个需要登录的网址时,系统会首先自动

    SharpZipLib 文件/文件夹压缩

    一.ZipFile ZipFile类用于选择文件或文件夹进行压缩生成压缩包. 常用属性: 属性 说明 Count 文件数目(注意是在ComitUpdat之后才有) Password 压缩包密码 Size 压缩包占用空间大小 Name 压缩包名称,默认输出是文件路径 ZipEntry 压缩包里的文件,通过索引[]访问 其常用方法如下: 方法 说明 Add 添加要进行压缩的文件 AddDirectory 添加文件夹(不会压缩文件夹里的文件) Delete 删除文件或文件夹 BeginUpdate 开

    “源文件与模块生成时的文件不同”解决方案

    问题: 在做BS项目的时候,出现的问题,就是服务器中的代码我们修改了之后,在用client端通过WCF服务调用Service端的时候,出现了这样的问题就是:"源文件与模块生成时的文件不同".其实,我觉得这个问题很简单,就是我们在修改了Service端的代码之后,Client端没有进行更新,它调用的是没有修改过的Serivce文件,会出现下面这样的错误. 调用的时候,我将服务器端的代码修改了,而客户端并没有及时的更新.我们细看一下这个问题是这样的: 方法一: 我用的最快的方法就是在&qu

    【Python】Python的urllib模块、urllib2模块进行网页下载文件

    由于需要从某个网页上下载一些PDF文件,但是需要下载的PDF文件有几百个,所以不可能用人工点击来下载.正好Python有相关的模块,所以写了个程序来进行PDF文件的下载,顺便熟悉了Python的urllib模块和ulrllib2模块. 1.问题描述 需要从http://www.cvpapers.com/cvpr2014.html上下载几百个论文的PDF文件,该网页如下图所示: 2.问题解决 通过结合Python的urllib模块和urllib2模块来实现自动下载.代码如下: test.py #!