zoukankan      html  css  js  c++  java
  • Python的路径操作(os模块与pathlib模块)

               Python的路径操作(os模块与pathlib模块)

                                          作者:尹正杰

    版权声明:原创作品,谢绝转载!否则将追究法律责任。

    一.os.path模块(Python 3.4版本之前推荐使用该模块)

    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    from os import path
    
    p = path.join("C:Windows","System32","drivers","etc")
    
    print(type(p),p)
    
    print(path.exists(p))                   #判断路径p是否存在
    
    print(path.split(p))                    #将路径进行切分,需要注意的是,windows和Linux切分方式可能不太一样
    
    print(path.abspath("."))                #打印当前的绝对路径
    
    print(path.join("/",p,"hosts"))         #将路径进行拼接
    
    print(path.dirname(p))                  #父目录
    
    print(path.basename(p))                 #最末层的目录
    
    print(path.splitdrive(p))               #获取驱动器名称,该方法一般用在windows操作系统,可以一目了然的看出来某目录的驱动器名称
    
    
    
    
    #以上代码输出结果如下:
    <class 'str'> C:WindowsSystem32driversetc
    True
    ('C:\Windows\System32\drivers', 'etc')
    D:Pythonproject自动化运维yinzhengjie_devopsday007
    C:WindowsSystem32driversetchosts
    C:WindowsSystem32drivers
    etc
    ('C:', '\Windows\System32\drivers\etc')
    #!/usr/bin/env python
    #_*_coding:utf-8_*_
    #@author :yinzhengjie
    #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
    #EMAIL:y1053419035@qq.com
    
    from os import path
    
    p1 = path.abspath(__file__)
    
    print(p1,path.basename(p1))
    
    while p1 != path.dirname(p1):
        p1 = path.dirname(p1)
        print(p1,path.basename(p1))
    
    
    #以上代码输出结果如下:
    D:Pythonproject自动化运维yinzhengjie_devopsday0071.path模块.py 01.path模块.py
    D:Pythonproject自动化运维yinzhengjie_devopsday007 day007
    D:Pythonproject自动化运维yinzhengjie_devops yinzhengjie_devops
    D:Pythonproject自动化运维 自动化运维
    D:Pythonproject project
    D:Python Python
    D: 
    遍历当前目录

    二.pathlib模块(Python 3.4版本开始建议使用pathlib模块,提供Path对象来操作。包括目录和文件)

    1>.初始化

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 """
     8     Python3.4版本开始,建议使用pathlib模块,提供Path对象来操作,包括目录和文件
     9 """
    10 
    11 from pathlib import Path
    12 
    13 
    14 p1 = Path()                     #当前目录
    15 
    16 p2 = Path('a','b','cd')        #当前目录下的"acd",我是在windows下执行的代码
    17 
    18 p3 = Path('/etc')               #根下的etc目录
    19 
    20 
    21 print("p1 = {}".format(p1))
    22 print("p2 = {}".format(p2))
    23 print("p3 = {}".format(p3))
    24 
    25 
    26 
    27 #以上代码执行结果如下:
    28 p1 = .
    29 p2 = acd
    30 p3 = etc

    2>.parts和joinpath属性

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 """
     8     Python3.4版本开始,建议使用pathlib模块,提供Path对象来操作,包括目录和文件
     9 """
    10 
    11 from pathlib import Path
    12 
    13 p = Path()
    14 
    15 p = p / 'a'
    16 
    17 p1 = 'b' / p
    18 
    19 p2 = Path('c')
    20 
    21 p3 = p2 / p1
    22 
    23 print(p3.parts)                                         #分解操作,可以返回路径中的每一个部分
    24 
    25 p4 = p3.joinpath('etc','init.d',Path('httpd'))          #连接多个字符串到Path对象中
    26 
    27 print("p1 = {},	 p1.parts = {}".format(p1,p1.parts))
    28 print("p2 = {},	 p2.parts = {}".format(p2,p2.parts))
    29 print("p3 = {},	 p3.parts = {}".format(p3,p3.parts))
    30 print("p4 = {},	 p4.parts = {}".format(p4,p4.parts))
    31 
    32 
    33 
    34 
    35 #以上代码执行结果如下:
    36 ('c', 'b', 'a')
    37 p1 = ba,     p1.parts = ('b', 'a')
    38 p2 = c,     p2.parts = ('c',)
    39 p3 = ca,     p3.parts = ('c', 'b', 'a')
    40 p4 = caetcinit.dhttpd,     p4.parts = ('c', 'b', 'a', 'etc', 'init.d', 'httpd')

    3>.获取路径

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 """
     8     Python3.4版本开始,建议使用pathlib模块,提供Path对象来操作,包括目录和文件
     9 """
    10 
    11 from pathlib import Path
    12 
    13 
    14 p1 = Path("C:WindowsSystem32driversetchosts")
    15 
    16 print(str(p1))              #获取路径字符串
    17 
    18 print(bytes(p1))            #获取路径字符串的bytes
    19 
    20 
    21 
    22 #以上代码执行结果如下:
    23 C:WindowsSystem32driversetchosts
    24 b'C:\Windows\System32\drivers\etc\hosts'

    4>.父目录

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 """
     8     Python3.4版本开始,建议使用pathlib模块,提供Path对象来操作,包括目录和文件
     9 """
    10 
    11 from pathlib import Path
    12 
    13 
    14 p1 = Path("C:WindowsSystem32driversetchosts")
    15 
    16 print(p1.parent.parent)     #目录的逻辑父目录
    17 
    18 
    19 for item in p1.parents:     #父目录序列,索引0是直接的父目录
    20     print(item)
    21     
    22     
    23 
    24 #以上代码执行结果如下:
    25 C:WindowsSystem32drivers
    26 C:WindowsSystem32driversetc
    27 C:WindowsSystem32drivers
    28 C:WindowsSystem32
    29 C:Windows
    30 C:

    5>.name,stem,suffix,suffixes.with_suffix(fuffix),with_name(name)

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 """
     8     Python3.4版本开始,建议使用pathlib模块,提供Path对象来操作,包括目录和文件
     9 """
    10 
    11 from pathlib import Path
    12 
    13 
    14 p1 = Path("C:WindowsSystem32driversetchosts.txt")
    15 
    16 print(p1.name)                          #获取目录的最后一个部分
    17 print(p1.suffix)                        #目录中最后一个部门的扩展名称,可以为空
    18 print(p1.suffixes)                      #返回多个扩展名列表
    19 print(p1.stem)                          #目录最后一个部分,没有后缀
    20 print(p1.with_name("protocol"))         #替换目录最后一个部分并返回一个新的路径
    21 
    22 p2 = Path("C:WindowsSystem32driversetcservices")
    23 print(p2.with_suffix(".txt"))           #补充扩展名到路径末尾,返回新的路径,扩展名存在则无效
    24 
    25 
    26 
    27 #以上代码执行结果如下:
    28 hosts.txt
    29 .txt
    30 ['.txt']
    31 hosts
    32 C:WindowsSystem32driversetcprotocol
    33 C:WindowsSystem32driversetcservices.txt

    6>.目录的常用方法

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 """
     8     Python3.4版本开始,建议使用pathlib模块,提供Path对象来操作,包括目录和文件
     9 
    10 cwd()
    11     返回当前工作目录
    12 home()
    13     返回当前家目录
    14 is_dir()
    15     是否是目录,目录存在返回True
    16 is_file()
    17     是否是普通文件,文件存在返回True
    18 is_symlink()
    19     是否是软连接
    20 is_socket()
    21     是否是socket文件
    22 is_block_device()
    23     是否是块设备
    24 is_char_device()
    25     是否是字符设备
    26 is_absolute()
    27     是否是绝对路径
    28 resolve()
    29     返回一个新的路径,这个新路径就是当前Path对象的绝对路径,如果是软连接则直接被解析
    30 absolute()
    31     也可以获取绝对路径,但是推荐使用resolve()
    32 exists()
    33     目录或文件是否存在
    34 rmdir()
    35     删除空目录。没有提供判断目录为空的方法
    36 touche(mode=0o666,exist_ok=True)
    37     创建一个文件
    38 as_uri()
    39     将目录返回成URL,例如:"file:///etc/hosts"
    40 mkdir(mode=0o777,partents=False,exist_ok=Flase)
    41     parents,是否创建父目录,True等同于mkdir -p;Flase时,父目录不存在,则抛出FileNotFountError,exist_ok参数,在3.5版本加入。Flase时,路径存在,抛出FileExistsError;True时,FileExistsError被忽略。
    42 iterdir()
    43     迭代当前目录
    44 """
    45 
    46 from pathlib import Path
    47 
    48 
    49 p1 = Path()
    50 
    51 p1 /= 'a/b/c/d'
    52 
    53 p1.exists()
    54 
    55 #创建目录
    56 # p1.mkdir()                #FileNotFoundError
    57 
    58 p1.mkdir(parents=True)
    59 p1.exists()
    60 
    61 p1.mkdir(parents=True,exist_ok=True)
    62 
    63 p1 /= "README.txt"
    64 
    65 p1.parent.rmdir()
    66 
    67 p1.parent.exists()
    68 
    69 # p1.mkdir()                #FileNotFoundError
    70 
    71 p1.mkdir(parents=True)
    72 
    73 
    74 #遍历,并判断文件类型,如果是目录是否可用判断其为空
    75 for x in  p1.parents[len(p1.parents)-1].iterdir():
    76     print(x,end='	')
    77     if x.is_dir():
    78         flag = False
    79         for _ in x.iterdir():
    80             flag = True
    81             break
    82         print("dir", "Not Empty" if flag else "Empyt", sep='	')
    83     elif x.is_file():
    84         print("file")
    85     else:
    86         print("other file")

    7>.通配符

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 """
     8     Python3.4版本开始,建议使用pathlib模块,提供Path对象来操作,包括目录和文件
     9 
    10 glob(pattern)
    11     通配符给定的模式
    12 rglob(pattern)
    13     通配符给定的模式,递归目录,返回一个生成器
    14 """
    15 
    16 from pathlib import Path
    17 
    18 
    19 p1 = Path("C:WindowsSystem32driversetc")
    20 
    21 print(list(p1.glob("host*")))         #返回当前目录对象下的以host开头的文件
    22 
    23 print(list(p1.glob("**/*.ddl")))      #递归所有目录,等同于rglob
    24 
    25 g = p1.rglob('host*')                 #生成器
    26 
    27 for _ in g:
    28     print(next(g))
    29 
    30 
    31 
    32 #以上代码执行结果如下:
    33 [WindowsPath('C:/Windows/System32/drivers/etc/hosts'), WindowsPath('C:/Windows/System32/drivers/etc/hosts.dz')]
    34 []
    35 C:WindowsSystem32driversetchosts.dz

    8>.匹配

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 """
     8     Python3.4版本开始,建议使用pathlib模块,提供Path对象来操作,包括目录和文件
     9 
    10 match(pattern)
    11     模式匹配,成功返回True
    12 """
    13 
    14 from pathlib import Path
    15 
    16 p1 = Path('D:Pythonprojectyinzhengjie_devopsday0071.pathlib_demo.py')
    17 
    18 
    19 print(p1.match("*.py"))
    20 
    21 print(p1.match("day0071.pathlib_demo.py"))
    22 
    23 print(p1.match("D:**project****1.pathlib_demo.py"))
    24 
    25 print(p1.match("**1.pathlib_demo.py"))
    26 
    27 print(p1.match("**.py"))
    28 
    29 
    30 #以上代码执行结果如下:
    31 True
    32 True
    33 True
    34 True
    35 True

    9>.stat()方法

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 """
     8     Python3.4版本开始,建议使用pathlib模块,提供Path对象来操作,包括目录和文件
     9 stat()
    10     相当于stat命令
    11     last()同stat(),但如果是符号链接,则显示符号链接本身的文本信息
    12 """
    13 
    14 from pathlib import Path
    15 
    16 p1 = Path("/yinzhengjie/softwares/mysql-5.7.25-linux-glibc2.12-x86_64")
    17 
    18 print(p1.stat())
    19 
    20 p2 = Path("/yinzhengjie/softwares/mysql")
    21 
    22 print(p2.stat())
    23 
    24 print(p2.lstat())

    10>.文件操作

     1 #!/usr/bin/env python
     2 #_*_coding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
     5 #EMAIL:y1053419035@qq.com
     6 
     7 
     8 """
     9     Python3.4版本开始,建议使用pathlib模块,提供Path对象来操作,包括目录和文件
    10 
    11 open(self, mode='r', buffering=-1, encoding=None,errors=None, newline=None)
    12     使用方法类似内奸函数open,返回一个文件对象。
    13 
    14 
    15 Python3.5增加的新函数
    16 read_bytes()
    17     以"rb"读取路径对应文件,并返回二进制流,可通过IDE去看源码。
    18 read_text(encoding=None,error=None)
    19     以"rt"方式读取路径对应文件,返回文本
    20 write_bytes(data)
    21     以"wb"方式写入数据到路径对应文件
    22 write_text(data,encoding=None,errors=None)
    23     以"wt"方式写入字符串到路径对应文件。
    24 """
    25 from pathlib import Path
    26 
    27 p1 = Path("my_binary_file")
    28 
    29 p1.write_bytes(b"https://www.cnblogs.com/yinzhengjie")
    30 
    31 print(p1.read_bytes())
    32 
    33 p2 = Path("my_text_file")
    34 
    35 p2.write_text("https://www.cnblogs.com/yinzhengjie")
    36 
    37 print(p2.read_text())
    38 
    39 with p2.open() as f:
    40     print(f.read(5))
    41 
    42 
    43 
    44 #以上代码执行结果如下:
    45 b'https://www.cnblogs.com/yinzhengjie'
    46 https://www.cnblogs.com/yinzhengjie
    47 https

     

    三.os模块其它常用方法

     1 #!/usr/bin/env python
     2 #_*_conding:utf-8_*_
     3 #@author :yinzhengjie
     4 #blog:http://www.cnblogs.com/yinzhengjie
     5 
     6 import os,sys
     7 
     8 
     9 path = r"C:WindowsSystem32driversetc"
    10 
    11 print(os.name)                        #windows是nt,Linux是posix。
    12 
    13 # print(os.uname())                   #unix/linux系统支持
    14 
    15 print(sys.platform)                   #windows显示win32,Linux显示Linux
    16 
    17 print(os.listdir(path))               #返回指定目录内容列表,不递归
    18 
    19 p1 = path + r"hosts"
    20 print(os.stat(p1))
    21 
    22 # print(os.chmod(p1,0O77))            #和Linux操作系统的chmod命令类似
    23 # print(os.chown(p1,uid=0,gid=0))     #和Linux操作系统的chown命令类似,可以改变文件的属主,属组,但需要足够的权限
    24 
    25 """
    26         os模块除了上面列举的还有很多,感兴趣的小伙伴可以在这个模块里找类似需求的方法,满足我们平时的开发基本上问题不大。
    27     对了,os模块也有open,read,write等方法,但是太底层,建议使用内建函数open,read,write,使用方法相似。
    28 """
  • 相关阅读:
    学习进度(2)
    模拟退火 [JSOI2004]平衡点 / 吊打XXX
    快读快写 O3 优化
    卡特兰数(Catalan)公式、证明、代码、典例
    树状数组 :单点修改,区间查询
    倍增 [模板]最近公共祖先LCA
    对测 【模拟】
    对测 【离线DP+二分】
    模拟退火 (骗分算法)
    基础数论入门
  • 原文地址:https://www.cnblogs.com/yinzhengjie/p/11070881.html
Copyright © 2011-2022 走看看