zoukankan      html  css  js  c++  java
  • os模块 -os_shutile模块

    一  os模块 对系统进行操作

    引入 import os

    1. system()  在python中执行系统命令

    # os.system("touch 1.txt")
    # os.system("ipconfig")
    # os.system("ifconfig")
    View Code

    2. popen() 执行系统命令返回对象,通过read方法读出字符串

    obj = os.popen('ifconfig')
    res = obj.read()
    print(res)
    View Code

    3. listdir()  获取指定文件夹中所有内容的名称列表

    lst = os.listdir('.')
    print(lst)
    View Code

    4. getcwd()  获取当前文件所在的默认路径

    # 路径
    res = os.getcwd()
    print(res)
    
    # 路径 + 文件
    print(__file__)
    View Code

    5. chdir()  修改当前文件工作的默认路径

    如果在这里面写上
    os.system('') 就相当于在这里面做操作
    View Code

    6. environ 获取或修改环境变量

    print(os.environ)
    print(os.environ["PATH"])
    os.environ["PATH"] += ":/home/wangwen/mysoft"
    os.system("wangwen")
    View Code

    7. name 获取系统标识

    linux.mac-> posix  windows-> 
    print(os.name)
    View Code

    8. sep 获取路径分割符号 

    linux,mac -> /       window-> 
    res = 'wangwen'+os.sep + 'notepad'
    print(repr(res))
    View Code

    9. linesep  获取系统的换行符号

    linux,mac -> 
        window->print(repr(os.linesep))
    View Code

    二 . os模块具有 新建/删除/

    引入 import os

    1. os.mknod   创建文件

    os.mknod('lianxi.py')
    View Code

    2. os.remove  删除文件

    os.remove('lianxi.py')
    View Code

    3.os.mkdir  创建目录(文件夹)

    os.mkdir("abc_ww")
    View Code

    4. os.rmdir   删除目录(文件夹)

    os.rmdir("abc_ww")
    View Code

    5. os.rename  对文件,目录重命名

    os.rename("lianxi1","lianxi2")
    View Code

    6. os.makedirs   递归创建文件夹

    os.makedirs("a/b/c/d/e/f/g")
    View Code

    7. os.removedirs 递归删除文件夹(空文件夹)

    os.removedirs("a/b/c/d/e/f/g")
    View Code

    三 . shutil模块 复制/移动

    引入 import shutil

    1. 复制内容

    fp1 = open('lianxi2',mode='r+',encoding='utf-8')
    fp2 = open('lainxi1.txt',mode='w',encoding='utf-8')
    shutil.copyfileobj(fp1,fp2)
    View Code

    2 copymode(src,dst)   #单纯的仅复制文件权限 , 不包括内容 

    """复制权限时,必须文件存在"""

    shutil.copymode("ceshi3.py","lianxi2")
    View Code

    3. copystat(src,dst)   #复制所有状态信息,包括权限,组,用户,修改时间等,不包括内容

    shutil.copystat("lianxi2","ceshi4.py")
    View Code

    4. copy 和 copy2

    #copy(src,dst)       #复制文件权限和内容
    # shutil.copy("lianxi2","ceshi5.py")
    
    #copy2(src,dst)      #复制文件权限和内容,还包括权限,组,用户,时间等
    # shutil.copy2("lianxi2","ceshi6.py")
    View Code

    5. 递归拷贝/删除

    #copytree(src,dst)   #拷贝文件夹里所有内容(递归拷贝)
    # shutil.copytree("ceshi777","ceshi666")
    
    #rmtree(path)        #删除当前文件夹及其中所有内容(递归删除)
    # shutil.rmtree("ceshi777")
    View Code

    6. 剪切

    #move(path1,paht2)   #移动文件或者文件夹
    # shutil.move("ceshi1.txt","pycharm-community-2020.1.3/ceshi2.ttt")
    View Code

    四. os路径模块 -os.path

    引入 import os.time

    1. basename() 返回文件名部分

    res = os.path.basename(pathvar)
    print(res)
    View Code

    2. dirname()  返回路径部分

    res = os.path.dirname(pathvar)
    print(res)
    View Code

    3 . split() 将路径拆分成单独的文件部分和路径部分 组合成一个元组

    tup = os.path.split(pathvar)
    print(tup)
    View Code

    4. join()  将多个路径和文件组成新的路径 可以自动通过不同的系统加不同的斜杠  linux / windows

    path1 = "home"
    path2 = "wangwen"
    path3 = "mysoft"
    # 方法一
    pathvar = path1 + os.sep + path2 + os.sep + path3
    print(pathvar)
    # 方法二(推荐)
    pathvar = os.path.join(path1,path2,path3)
    print(pathvar)
    View Code

    5 . getsize()  获取文件的大小 ***

    """getsize只能获取文件大小,不能获取文件夹的大小"""

    print(os.getcwd())
    pathvar = os.path.join(os.getcwd(),"1.txt") # /mnt/hgfs/python33_gx/day17/1.txt
    print(pathvar)
    res = os.path.getsize(pathvar)
    print(res)
    View Code

    7. isdir()    检测路径是否是一个文件夹 ***

    pathvar = os.path.join(os.getcwd(),"1.txt") # /mnt/hgfs/python33_gx/day17/1.txt
    res = os.path.isdir(pathvar)
    print(res)
    View Code

    8. isfile()   检测路径是否是一个文件 ***

    res = os.path.isfile(pathvar)
    print(res)
    View Code

    9. islink()   检测路径数否是一个链接 **

    res = os.path.islink("/home/wangwen/ceshi03/ceshi01")
    print(res)
    View Code

    10. getctime() [windows]文件的创建时间,[linux]权限的改动时间(返回时间戳) **

    res = os.path.getctime("ceshi2.py") 
    print(res) 
    View Code

    11 getmtime() 获取文件最后一次修改时间(返回时间戳) **

    res = os.path.getmtime("ceshi2.py") 
    print(res) 
    View Code

    12 getatime() 获取文件最后一次访问时间(返回时间戳) **

    res = os.path.getatime("ceshi2.py") 
    print(res) 
    View Code

    13 exists()   检测指定的路径是否存在 ***

    res = os.path.exists("ceshi4.py")
    print(res)
    View Code

    14. isabs()    检测一个路径是否是绝对路径 *** 

    pathvar = "."
    res = os.path.isabs(pathvar)
    print(res)
    View Code

    15 .abspath()  将相对路径转化为绝对路径 ***

    res = os.path.abspath(pathvar)
    print(res)
    View Code

    五 . 小练习 计算文件的大小

    def getallsize(pathvar):
        size = 0
        lst = os.listdir(pathvar)
        for i in lst:
            pathnew = os.path.join(pathvar,i)
            if os.path.isdir(pathnew):
                size += getallsize(pathnew)
            elif os.path.isfile(pathnew)
                size += os.path.getsize(pathnew)
    
        return size
    
    res = getallsize(pathvar)
    print(res)
    View Code

    六 . tarfile 模块

    import tarfile

    1.创建tar包

    # 1.创建压缩包
    tf = tarfile.open("ceshi1210.tar","w",encoding="utf-8")
    # 2.写入文件
    tf.add("/bin/cat","cat")
    tf.add("/bin/chacl","chacl")
    tf.add("/bin/cp","tmp/cp")
    tf.add("/aaabbb","aaabbb") #可直接压缩文件夹
    # 3.关闭文件
    tf.close() # 225,280 

    2.创建.tar.gz包

    tf = tarfile.open("ceshi1210.tar.gz","w:gz",encoding="utf-8")
    tf.add("/bin/cat","cat")
    tf.add("/bin/chacl","chacl")
    tf.add("/bin/cp","tmp/cp")
    tf.add("/aaabbb","aaabbb")
    tf.close() # 96,797

    3.创建.tar.bz2包

    tf = tarfile.open("ceshi1210.tar.bz2","w:bz2",encoding="utf-8")
    tf.add("/bin/cat","cat")
    tf.add("/bin/chacl","chacl")
    tf.add("/bin/cp","tmp/cp")
    tf.add("/aaabbb","aaabbb")
    tf.close() # 84078

    4 .解压文件

    tf = tarfile.open("ceshi1210.tar.bz2","r",encoding="utf-8")
    # 解压所有
    # tf.extractall("ceshi1210")
    # 解压单个(落脚在文件身上)
    tf.extract("aaabbb/1.py","ceshi1210_1")
    tf.close()

    5 . 查看文件 (使用with语法)

    with tarfile.open("ceshi1210.tar.bz2","r",encoding="utf-8") as tf:
        lst = tf.getnames()
        print(lst)

    6 . 追加文件

    """无法对已经压缩过的压缩包做内容的追加;"""

    # with tarfile.open("ceshi1210.tar","a",encoding="utf-8") as tf:
        # tf.add("/bin/mv","mv") # success 
    
    # with tarfile.open("ceshi1210.tar.bz2","a",encoding="utf-8") as tf:
        # tf.add("/bin/mv","mv") # error

    7.解决办法

    """
    1.先解压
    2.将文件追加到该文件夹中
    3.在重新过滤打包即可
    """

    # 1.先解压文件
    with tarfile.open(pathvar1,"r",encoding="utf-8") as tf:
        tf.extractall("ceshi1210_2")
    
    # 2.将文件追加到该文件夹中
    shutil.copy("/bin/nano",pathvar2)
    
    # 3.在重新过滤打包即可
    """过滤掉cat,剩下的数据打包"""
    lst = os.listdir(pathvar2)
    print(lst) # ['aaabbb', 'cat', 'chacl', 'nano', 'tmp']
    
    
    with tarfile.open(pathvar1,"w:bz2",encoding="utf-8") as tf:
        for i in lst:
            if i != "cat":
                # 拼接好完整绝对路径
                pathvar = os.path.join(pathvar2,i)
                # 添加到压缩包中
                tf.add(pathvar,i)
  • 相关阅读:
    【基础知识】文件的读写操作
    【基础知识】winfrom窗体的属性
    【基础知识】ASP.NET[基础一(ashx)]
    【基础知识】Dom基础
    【基础知识】JavaScript基础
    【基础知识】C#数据库中主键类型的选择
    【基础知识】ASP.NET[基础二(aspx)]
    fileUpload上传文件,并设置文件名以及保存服务器位置
    list转成json,json转成list
    一个checkbox 用jquery实现全选、全不选
  • 原文地址:https://www.cnblogs.com/whc6/p/14117574.html
Copyright © 2011-2022 走看看