pathlib: Swiss army knife handle file paths

pathlib python3.4 module is introduced, specifically for the processing path. Personally think that this is a very, very powerful module, can be said processing path of a Swiss Army knife, let's take a look at its features.

在pathlib中有一个Path这个类,我们所做的所有操作都是基于这个类来的。

Path instance objects

from pathlib import Path

path = Path(r"c:\python37\lib\site-packages\tornado")
print(path)  # c:\python37\lib\site-packages\tornado
print(type(path))  # <class 'pathlib.WindowsPath'>
"""
可以看到打印的时候,和普通字符串输出是一样的,但是类型是<class 'pathlib.WindowsPath'>
如果是在linux下则是<class 'pathlib.PosixPath'>
"""

Operating path

from pathlib import Path

path = Path(r"c:\python37\lib\site-packages\tornado")
# 如果我要找到c:\python37\lib\site-packages\flask怎么做呢?
# 使用os的话,os.path.join(os.path.dirname(os.path.abspath(r'c:\python37\lib\site-packages\tornado')), 'flask')

# 使用os的话,会很长,但是使用path会很简单
# 我们调用path.parent等于回到路径的上一层,注意:得到的还是Path对象
# 这就意味着我们可以不断的使用parent
print(path.parent)  # c:\python37\lib\site-packages

# 我们也可以对path使用join的模式
print(path.parent.joinpath("flask"))  # c:\python37\lib\site-packages\flask

# 除此之外,还有更简单的办法
print(path.parent / 'flask')  # c:\python37\lib\site-packages\flask
print(path.parent.parent.parent / 'scripts' / "pip.exe")  # c:\python37\scripts\pip.exe

"""
怎么样呢?是不是很方便呢?
只不过得到的都是Path对象,如果需要当成普通的字符串来使用的话,还需要使用str转化一下。
"""

Related operations

from pathlib import Path

path = Path(r"c:\python37\lib\asyncio\__init__.py")
# Path在拼接路径的时候,即使路径不存在也是可以的。只是单纯的当成普通字符串来处理
# 但是当输入存在的路径的时候,我们还可以进行处理

# 1.打印当前的path的绝对路径
print(path.absolute())  # c:\python37\lib\asyncio\__init__.py

# 2.Windows下的话,打印根目录,个人觉得没啥卵用
print(path.anchor)  # c:\

# 3.转化为unix的路径,个人觉得没啥卵用
print(path.as_posix())  # c:/python37/lib/asyncio/__init__.py

# 4.转化成文件模式的路径,注意:在pycharm点击是可以直接跳转的
print(path.as_uri())  # file:///c:/python37/lib/asyncio/__init__.py

# 5.改变文件权限,在Windows下无卵用
# path.chmod(755)

# 6.打印文件的工作区,也就是所在目录。相当于path.parent
print(path.cwd())  # D:\koishi

# 7.Windows下打印所在盘符
print(path.drive)  # c:

# 8.打印文件所在的组,Windows下会报错,只在POSIX下有用
# print(path.group())

# 9.打印家目录,这个功能和传入Path里面的路径没太大关系
print(path.home())  # C:\Users\satori

# 10.判断当前路径是否是绝对路径
print(path.is_absolute())  # True

# 11.判断是否是目录
print(path.is_dir())  # False

# 12.判断是否是文件
print(path.is_file())  # True

# 13.判断是否存在
print(path.exists())  # True

# 14.打印文件名
print(path.name)  # __init__.py

# 15.文件的所有者,Windows不支持
# print(path.owner())

# 16.将路径进行肢解(好残忍,(゚Д゚))
print(path.parts)  # ('c:\\', 'python37', 'lib', 'asyncio', '__init__.py')

# 17.给文件重命名
# print(path.rename("new_name"))  # 这里不改了,因为是python的内置模块

# 18.查看文件属性,等同于os.stat("path")
print(path.stat().st_size)  # 1212

# 19.不要后缀名
print(path.stem)  # __init__

# 20.打印后缀名
print(path.suffix)  # .py

# 21.以字节的形式读取
# print(path.read_bytes())
"""
def read_bytes(self):
    with self.open(mode='rb') as f:
        return f.read()
"""

# 22.以文本形式读取
# print(path.read_text())
"""
def read_text(self, encoding=None, errors=None):
    with self.open(mode='r', encoding=encoding, errors=errors) as f:
        return f.read()
"""

# 23.以字节形式写入
# path.write_bytes()
"""
def write_bytes(self, data):
    view = memoryview(data)
    with self.open(mode='wb') as f:
        return f.write(view)
"""

# 24.以文本形式写入
# path.write_text()
"""
def write_text(self, data, encoding=None, errors=None):
    if not isinstance(data, str):
        raise TypeError('data must be str, not %s' %
                        data.__class__.__name__)
    with self.open(mode='w', encoding=encoding, errors=errors) as f:
        return f.write(data)
"""
# 可以看到read_bytes,read_text,write_bytes,write_text底层都是调用了open方法


# 25.遍历文件
path = Path(r"c:\python37\lib\site-packages\pandas")
# 找到所有以.py结尾的文件
for p in path.glob("*.py"):
    print(p)
    r"""
    c:\python37\lib\site-packages\pandas\conftest.py
    c:\python37\lib\site-packages\pandas\testing.py
    c:\python37\lib\site-packages\pandas\_version.py
    c:\python37\lib\site-packages\pandas\__init__.py
    """

# 26.递归遍历文件
for p in path.rglob("???.py"):
    # 找到文件名是3个字符加上.py的文件
    # 注意:glob和rglob匹配的时候,是按照文件名匹配的。
    # 但是遍历得到的是包含文件所在路径的,换句话说会将Path里面的路径和其里面符合匹配格式的文件组合起来。
    print(p)
    r"""
    c:\python37\lib\site-packages\pandas\core\api.py
    c:\python37\lib\site-packages\pandas\core\ops.py
    c:\python37\lib\site-packages\pandas\core\computation\api.py
    c:\python37\lib\site-packages\pandas\core\computation\ops.py
    c:\python37\lib\site-packages\pandas\core\dtypes\api.py
    c:\python37\lib\site-packages\pandas\core\groupby\ops.py
    c:\python37\lib\site-packages\pandas\core\indexes\api.py
    c:\python37\lib\site-packages\pandas\core\reshape\api.py
    c:\python37\lib\site-packages\pandas\core\sparse\api.py
    c:\python37\lib\site-packages\pandas\io\api.py
    c:\python37\lib\site-packages\pandas\io\gbq.py
    c:\python37\lib\site-packages\pandas\io\gcs.py
    c:\python37\lib\site-packages\pandas\io\sql.py
    c:\python37\lib\site-packages\pandas\io\formats\css.py
    c:\python37\lib\site-packages\pandas\tests\extension\base\ops.py
    c:\python37\lib\site-packages\pandas\tseries\api.py
    """

以上是关于pathlib的介绍,尽管Path有很多种,WindowsPath,PosixPath,PurePath,但是我们操作的时候操作Path这个类即可,会自动帮我们选择符合平台的Path。Path类的属性并没有全部介绍完,因为很多不是很常用。并且我觉得最重要的还是对路径的处理,其他的都是对一些底层模块的封装。

About Path class all the properties below, are interested, you can see the source code to continue in-depth look

for attr in dir(Path):
    if not attr.startswith("_"):
        print(attr)
        """
        absolute
        anchor
        as_posix
        as_uri
        chmod
        cwd
        drive
        exists
        expanduser
        glob
        group
        home
        is_absolute
        is_block_device
        is_char_device
        is_dir
        is_fifo
        is_file
        is_mount
        is_reserved
        is_socket
        is_symlink
        iterdir
        joinpath
        lchmod
        lstat
        match
        mkdir
        name
        open
        owner
        parent
        parents
        parts
        read_bytes
        read_text
        relative_to
        rename
        replace
        resolve
        rglob
        rmdir
        root
        samefile
        stat
        stem
        suffix
        suffixes
        symlink_to
        touch
        unlink
        with_name
        with_suffix
        write_bytes
        write_text
        """

Guess you like

Origin www.cnblogs.com/traditional/p/11441264.html