zoukankan      html  css  js  c++  java
  • python入门之sys模块、shutil模块

    sys模块

    import sys
    
    sys.version              返回python的版本
    sys.argv                 返回一个以脚本名,和传入的参数作为元素的列表
    sys.path                 返回一个以当前代码文件路径,python安装的路径,以及第三方库存放路径
    sys.path.append("/opt")  添加路径
    sys.exit(a)              退出程序,输出字符串,正常退出时exit(0)
    sys.platform             返回操作系统平台名称
    sys.stdout.write("hello")打印hello,但是末尾没有换行
    sys.stdout.flush()       刷新缓冲区,强制刷新到屏幕

    shutil模块

    import shutil
    
    f1 = open("file1",encoding="utf-8")
    f2 = open("file2","w",encoding="utf-8")
    
    shutil.copyfileobj(f1,f2)          将文件内容拷贝到另一个文件中,可以部分内容
    shutil.copyfile("file1","file2")   直接拷贝文件
    shutil.copymode("file1","file2")   仅拷贝权限。内容、组、用户均不变
    shutil.copystat("file1","file2")   拷贝所有状态信息
    shutil.copy("file1","file2")       拷贝文件和权限
    shutil.copy2("file1","file2")      拷贝文件和状态信息
    shutil.copytree("dir1","dir2")     拷贝目录,递归拷贝目录下所有文件
    shutil.rmtree("dir2")              删除目录,包括目录下所有文件
    shutil.move(src,dst)               递归的移动文件
    
    shutil.make_archive(base_name,format,...)   创建压缩包
        base_name:压缩包的文件名,也可以压缩包的路径。保存至当前目录,是路径就保存至路径
        format:压缩包的种类,zip,tar,bztar,gztar
        root_dir:要压缩的文件夹路径(默认当前目录)
        owner:用户,默认当前用户
        group:组,默认当前组
        logger:用于记录日志,通常是logging.Logger对象
    eg: shutil.make_archive("packname","zip","/opt/data")  将/opt下的data目录打包成packname.zip包,放在当前目录

     shutil对压缩包的解压处理

    import zipfile
    #压缩
    a = zipfile.ZipFile('test.zip','w')  #压缩当前目录下的文件,可以选择压缩
    a.write('test1.log')
    print("test1.log压缩完成")
    a.write('test2.log')
    print("test2.log压缩完成")
    a.close()
    #解压
    a = zipfile.ZipFile('test.zip','r')
    a.extractall()
    a.close()
    
    ############################################
    
    import tarfile
    #压缩
    a = tarfile.open('test.tar','w')  #压缩当前目录下的文件,可以选择压缩
    a.add('/test/test1.log',arcname='test1.log')
    a.add('/test/test2.log',arcname='test2.log')
    a.close()
    #解压
    a = tarfile.open('test.tar,'r')
    a.extractall()            #可设置解压地址
    a.close()
  • 相关阅读:
    巴洛克式和哥特式的区别
    推荐阅读书籍,是时候再行动起来了。
    AtCoder ABC 159F Knapsack for All Segments
    AtCoder ABC 159E Dividing Chocolate
    AtCoder ABC 158F Removing Robots
    AtCoder ABC 158E Divisible Substring
    AtCoder ABC 157F Yakiniku Optimization Problem
    AtCoder ABC 157E Simple String Queries
    AtCoder ABC 157D Friend Suggestions
    AtCoder ABC 156F Modularness
  • 原文地址:https://www.cnblogs.com/chy-op/p/10537718.html
Copyright © 2011-2022 走看看